// 电子病历公共组件
import React from 'react';
import SettingsDocumentSize from '../emr/component/SettingsDocumentSize';
import { Dropdown, Button, Select, Icon, Divider, Menu, Modal, Tree, message, Popconfirm, Input, Row, Col, Checkbox, Tabs, Table, Tooltip, Upload } from 'antd';
import ColorPickup from '../emr/component/ColorPickup.jsx';
import CourseOfDiseaseTemplate from 'pages/common/CourseOfDiseaseTemplate.jsx';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import { Util, ArraySome } from 'tools';
import PublicModalFormHooks from './PublicModalFormHooks';
import PubilcTablePagination from './PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CaseInformationPageTabs from 'pages/workstation/component/CaseInformationPageTabs.jsx';
import ShowDiagnosisModal from './ShowDiagnosisModal.jsx';
import DoctorAdviceStepPage from 'pages/workstation/component/DoctorAdviceStepPage';
import EMRFindReplace from 'pages/emr/component/EMRFindReplace.jsx';
import UpdateTemplateData from 'pages/emr/component/UpdateTemplateData.jsx';
import './style/index.less';
import '../departmentInformation/style/index.less'; // 科室列表样式

const { TreeNode } = Tree;
const TabPane = Tabs.TabPane;
let { Option } = Select;
const { confirm } = Modal;
let initCtl = 0;
let initHandleInit = 0;
let courseOfDiseaseTemplateCount = 0;

/**
输入：
	需要传入一个名为 param 的对象，对象包含的参数如下：
		1、formView = 'Normal' --- 为表单模式，书写模式可不传
		2、isInsert = 'hidden' --- 是否显示按钮操作栏，需要显示则不传
		3、headerFooterEditable --- 传'noEditable'即不可编辑页眉页尾，不传则可操作
		4、isNewFile --- 传true即不显示
		……同4

	方法(传了对映的方法才会显示对映的按钮)：
		1、handleSave --- 为保存方法，必传
		2、onRef --- 为父组件调用子组件的方法，必传
		3、handleRelease --- 发布，
		4、handleDelete --- 删除


	控制台下载xml方法 document.WriterControl.DownLoadFile('xml');
	控制台打印xml方法 let str = document.WriterControl.SaveDocumentToString('xml');
	控制台选择xml进行加载：document.WriterControl.DCExecuteCommand('fileopen',true,null);
	控制台加载XML document.WriterControl.DCExecuteCommand('fileopen');
	查看当前模板信息: document.WriterControl.AboutControl();
输出：
*/

export default class ElectronicCaseTemplate extends React.Component {
	constructor(props) {
		super(props);
		// EMRTest
		let EMRIP = window.location && (window.location.host.indexOf('localhost') !== -1 || window.location.host.indexOf('127.0.0.1') !== -1) ? 'https://172.16.1.6/EMR' : (window.location.protocol + '//' + window.location.host + '/EMR');
		let recordData = JSON.parse(sessionStorage.getItem('patientData'));
		let userData = JSON.parse(sessionStorage.getItem('userData'));
		let sessionZoom = React.$getLocalStorageData('ElectronicCaseTemplate_zoom', false);
		this.state = {
			ipConfig: React.$getSessionData('ipConfig'),
			recordData,
			userData,
			EMRIP,
			fontTyle: undefined,
			fontColor: '#000',
			fontSize: undefined,
			isColorPickup: false,
			insertTemplateArr: [], // 插入的数据集
			counterObj: {}, // 计数器对象
			selectionXml: '', // 被选中的xml
			visible: false,
			modalSelectedKeys: [],
			modalTreeSelectData: {},
			dbModalId: '', // 双击模板中的输入域ID
			customDataSet: [], // 自定义数据集
			isOperable: 'Y',
			customDataTableData: [], // 自定义下拉列表数据
			templateErrorMes: '',
			readNum: 1,
			readingHistory: false,
			courseOfDiseaseVisible: false,
			courseOfDiseaseValue: undefined,
			versionID: '',
			templateID: '', // 模板ID
			templateSelectData: [],
			dropDownSearch: false, // 下拉搜索
			selectCode: undefined,
			selectDesc: undefined,
			selectRowData: {},
			modalTableData: [],
			modalTotal: 0,
			modalPage: 1,
			modalPageSize: 20,
			modalLoading: false,
			modalRowId: '',
			modalRowData: '',
			columns: [],
			forcedPageChange: false, // 插入的病程是否强制分页
			newSource: '', // 病程插入来源
			printSpecifiedPage: [], // 指定打印页
			pageNum: 1,
			diagnosisSearch: false, // 诊断弹窗
			diagnosisRowData: {}, // dataSource-诊断行数据
			historicalKnowledgeBase: false, // 历史知识库
			activeTabs: '1', //
			contentChangeVisible: false,
			contentChangeTableData: [],
			contentChangeTotal: 0,
			contentChangLoading: false,
			contentChangeSelectedRowKeys: [],
			contentChangSelectedRows: [],
			isModifyPermissions: 'N',
			isPrintPreview: 'N',
			progressID: '',
			forceUnlock: 'N', // 是否强制解锁
			IDCollection: [], // 动态下拉弹窗选择的数据id对应输入域id呈数组对象 fieldID, valueID
			basicID: '',
			medicalOrderVisible: false, // 医嘱录入弹窗
			pasteFormat: 'N', // 粘贴格式
			templateParams: {},
			ruleOfReferences: '', // 医嘱引用规则
			dblclickDOM: '',
			courseOfDiseaseDataSource: [],
			courseOfDiseaseFlag: 'N', // 病程标志
			uploadBtnLoading: false,
			saveBtnLoading: false,
			DRGVisible: false,
			DRGUrl: '',
			courseOfDiseaseLoading: false, // 病程确认 - 加载完之后才能点击
			syncNotice: false, // 不再提醒同步须知
			ajaxLoadCount: 0, // 加载模板次数，加载失败超过五次提示加载失败
			loadXMLStr: '', // 保存为范例病历需加载当前界面xml
			newPageFormData: [],
			newPageRowData: {},
			scaleZoom: sessionZoom || undefined, // 缩放
			lineSpace: undefined, // 行间距
		};

		this.editorID = this.props.editorID ? this.props.editorID : 'myWriterControl';
		this.columns = [
			{ title: '代码', dataIndex: 'code', key: '2', width: '100px', align: 'center' },
			{ title: '描述', dataIndex: 'descripts', key: '3', width: '200px', align: 'center' },
		];
		this.contentChangeColumns = [
			{ title: '代码', dataIndex: 'fieldID', key: '1', width: '100px', align: 'center' },
			{ title: '名称', dataIndex: 'fieldName', key: '2', width: '100px', align: 'center' },
			{ title: '数据', dataIndex: 'displayValue', key: '3', width: '200px', align: 'center' },
		];
	}

	componentDidMount() {
		this.props.onRef(this);
		Promise.all([this.importService(), this.importJquery()])
			.then(() => {
				setTimeout(() => {
					this.handleInit(true)
				}, 800)
			})
		this.getChineseAndEnglishData();
		this.getCustomDataTableData();
	}

	componentWillUnmount() {
		// 组件销毁时移除插入的script标签
		// document.getElementById('emr-jquery').remove();
		document.getElementById('emr-service').remove();
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => { return; }
	}

	// 获取中英文数据
	getChineseAndEnglishData = () => {
		let { userData } = this.state;
		let data = {
			params: [{
				compontName: 'ElectronicCaseTemplate',
				type: 'C',
				reactCode: ['ElectronicCaseTemplate']
			}]
		}
		$http.post('urlDeault', this, {
			code: '01040073',
			data: data,
			success: (res) => {
				if (res.errorCode === '0') {
					let columnsData = res.result.C && res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							// title: userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title,
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					this.setState({
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN,
						columns: columnsData,
						newPageFormData: res?.result?.formData || []
					})
				}
			}
		})
	}

	// 获取基础数据字典弹窗表头数据
	getModalColumns = (compontName) => {
		if (!compontName) {
			this.setState({ columns: [] });
			return;
		}
		let { userData } = this.state;
		let data = {
			params: [{
				compontName,
				type: 'C',
				reactCode: [compontName]
			}]
		}
		$http.post('urlDeault', this, {
			code: '01040073',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					let columnsData = res.result.C && res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							// title: userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title,
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					this.setState({
						columns: columnsData,
					})
				}
			}
		})
	}

	onMainColumnRef = ref => {
		this.mainColumnRef = ref;
	}

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
	}

	importJquery = () => {
		let jqDOM = document.getElementById('emr-jquery');
		if (!jqDOM) {
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.async = true;
			script.id = 'emr-jquery';
			// script.src = 'http://www.dcwriter.cn:6788/jquery/jquery-1.7.2.min.js ' // 都昌测试服务
			script.src = `${this.state.EMRIP}/jquery/jquery-1.7.2.min.js`; // www.dcwriter.cn、172..18.13.23:62535
			document.head.appendChild(script);
		}
	}

	importService = () => {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.async = true;
		script.id = 'emr-service';
		// script.src = 'http://www.dcwriter.cn:6788/ServicePage.aspx?js=1' // 都昌测试服务
		script.src = `${this.state.EMRIP}/DemoDocumentImageService.aspx?js=1`;
		document.head.appendChild(script);
	}

	changeBarcode = () => {
		var ctl = document.getElementById(this.editorID);
		let { insertTemplateArr } = this.state
		let newArr = insertTemplateArr && insertTemplateArr.length > 0 ? ArraySome.ArrayWeigh(insertTemplateArr, 'remove') : []; // 数组去重
		let flag = false;
		for (let i = 0; i < newArr.length; i++) {
			var tdbarcodeele = ctl && ctl.GetContentDocument && ctl.GetContentDocument() && ctl.GetContentDocument().getElementById && ctl.GetContentDocument().getElementById(newArr[i].fieldID);
			if (tdbarcodeele && tdbarcodeele.tagName === 'IMG') {
				flag = true;
				this.changeBarcodeImg(newArr[i].fieldID, newArr[i].displayValue)
				break;
			}
		}
		if (!flag) {
			setTimeout(() => {
				this.resetModified('noPage'); // 设置病历修改状态
			}, 300)
		}
	}

	changeBarcodeImg = (Id, No) => {
		var ctl = document.getElementById(this.editorID);
		var tdbarcodeele = ctl.GetContentDocument && ctl.GetContentDocument().getElementById(Id);

		var option = {
			ID: Id, //元素ID
			Text: No, //条形码文本
			Width: tdbarcodeele.width, //像素宽度
			Height: tdbarcodeele.height, //像素高度
			BarcodeStyle: 'Code128C', //条形码编码，必须符合DCSoft.Writer.Dom.DCBarcodeStyle枚举字符串
			Name: 'barcode1Name'//元素NAME
		};
		//返回二维码或者条形码元素
		// var ele = ctl.CreateBarcodeElement(option, true);// 二维码
		var div = document.createElement('div');
		div.id = 'div-' + Id;
		var ele2 = ctl.CreateBarcodeElement(option, false);//条形码
		var patNo = document.createElement('span');
		patNo.style.display = 'inline-block';
		patNo.className = 'create-barcode-elemen-span';
		patNo.id = 'span-' + Id;
		patNo.innerHTML = No;
		div.appendChild(ele2);
		// div.appendChild(patNo);
		var spanNode = tdbarcodeele.nextElementSibling;
		if (!spanNode) {
			div.appendChild(patNo);
		} else {
			spanNode.style.display = 'inline-block';
			spanNode.className = 'create-barcode-elemen-span';
		}
		tdbarcodeele.parentNode.replaceChild(div, tdbarcodeele);
		setTimeout(() => {
			this.resetModified('noPage'); // 设置病历修改状态
		}, 300)
		//返回二维码或者条形码元素
		// var ele2 = ctl.CreateBarcodeElement(option, true);//二维码
		// var ele2 = ctl.CreateBarcodeElement(option, true);//二维码
		// tdbarcodeele.parentNode.replaceChild(ele2, tdbarcodeele);
	}

	handleInit = (autoZoom) => {
		let { param } = this.props;
		let { userData, scaleZoom } = this.state;
		if (!(window && window.BindingDCWriterClientControl)) { // 初始化加载病历模板
			initHandleInit++;
			if (initHandleInit < 5) {
				setTimeout(() => {
					this.handleInit(true)
				}, 500);
			}
			return;
		}
		// 获得控件容器元素
		try {
			let _this = this;
			let ctl = document.getElementById(this.editorID);
			// 绑定控件
			window.BindingDCWriterClientControl(ctl);
			ctl.Options.autoZoom = autoZoom;
			ctl.Options.AutoFixFontSize9 = 9.1;
			param && param.formView === 'Normal' ? (ctl.Options.FormView = 'Normal') : ''; // 表单模式
			param && param.formView === 'Normal' ? (ctl.Options.FreeSelection = 'true') : ''; // 表单模式下，自由选择
			// param&&param.headerFooterEditable === 'noEditable' ? (ctl.Options.HeaderFooterEditable = 'false') : (ctl.Options.HeaderFooterEditable = 'true');// 页眉页尾是否可操作
			ctl.Options.HeaderFooterEditable = true
			ctl.DocumentOptions.ViewOptions.ShowCellNoneBorder = false; // 是否可以删除表格边框
			// ctl.DocumentOptions.ViewOptions.CopyWithoutInputFieldStructure = true; // 复制时去掉输入域层次结构(会影响病程插入进来其他效果，栗：两个输入域关联问题)
			ctl.DocumentOptions.ViewOptions.CopyInTextFormatOnly = true; // 仅仅采用纯文本格式复制内容,若为true，则只复制纯文本内容，而且忽略掉控件的CreationDataFormats属性设置
			// ctl.Options.ShowPageLineForEdit = 'true'; // 书写界面添加分页符【有些偏差，暂时不用这个功能】
			// 隐藏分页符
			ctl.Options.CustomCSSString = "[dctype='XTextPageBreakElement']{display:none;}";
			// 隐藏获取焦点时输入域边框问题
			ctl.Options.CustomCSSString += "*{outline:none;}";
			// 给病程按钮添加样式
			ctl.Options.CustomCSSString += `span[dctype='XTextLabelElement']#newtitle{height: 30px; line-height: 28px;border: 1px solid #40a9ff; color: #40a9ff;padding: 0px 8px;font-size: 12px;font-weight: bold;border-radius: 2px;box-sizing: border-box; display: inline-block;}
			#YGDCopyL,#YGDCopyS{border: 1px solid #40a9ff;color: #40a9ff;padding: 2px 8px;display: inline-block;border-radius: 2px;margin-top: 6px;cursor: pointer;}`;
			// .emr-common-select{padding-right: 18px;position: relative;} 
			// .emr-common-select:after{content: ' ';display: inline-block;position: absolute;right: 0;top: -8px;transform: rotate(314deg);height: 6px; width: 6px; border-width: 0 0 2px 2px;border-color: rgba(0, 0, 0, 0.25);border-style: solid;}`;

			// 设置控件属性
			ctl.DocumentOptions.BehaviorOptions.AcceptDataFormats = 'Text'; // 粘贴不带格式
			ctl.DocumentOptions.ViewOptions.ShowInputFieldStateTag = param && param.setChapter === 'show' ? false : true; // 输入域的扩展标志
			ctl.DocumentOptions.ViewOptions.FieldInvalidateValueBackColor = 'Yellow';
			ctl.DocumentOptions.ViewOptions.FieldFocusedBackColorValue = '#fff'; // 光标所在背景色
			ctl.DocumentOptions.ViewOptions.FieldHoverBackColorValue = '#fff';
			ctl.DocumentOptions.ViewOptions.FieldBackColorValue = '#fff'; // 文本输入域的默认背景颜色
			// ctl.DocumentOptions.ViewOptions.FieldFocusedBackColor = null;
			// 用Tab键在各个输入域之间切换
			ctl.DocumentOptions.BehaviorOptions.MoveFocusHotKey = 'Tab'; // 'Enter';
			ctl.DocumentOptions.ViewOptions.EnableEncryptView = false;
			ctl.DocumentOptions.ViewOptions.PrintBackgroundText = false;
			ctl.DocumentOptions.ViewOptions.PreserveBackgroundTextWhenPrint = true;
			//ctl.Options.FormView = 'Normal';
			ctl.ToolbarForPrintPreview = null;
			// 用户留痕
			// ctl.Options.LogUserEditTrack = 'true';
			// ctl.Options.CurrentUserID = userData?.userID || '';
			// ctl.Options.CurrentUserName = userData?.userName || '';
			// ctl.Options.CurrentUserPermissionLevel = '1';
			// ctl.Options.ClientMachineName = ipConfig?.mac || '';
			// ctl.Options.ExcludeLogicDeleted = true;
			// ctl.DocumentOptions.SecurityOptions.EnablePermission = true; // 是否启用权限校验，和 CurrentUserPermissionLevel 搭配使用。
			// ctl.DocumentOptions.SecurityOptions.EnableLogicDelete = true; // 是否启用逻辑删除
			// ctl.DocumentOptions.SecurityOptions.ShowLogicDeletedContent = false; // 是否显示逻辑删除内容，请设置为false。如果设置为true，可以在前端实现删除时实时留痕，但是不准确。
			// ctl.DocumentOptions.SecurityOptions.ShowPermissionMark = false; // 是否显示权限记录，请设置为false。
			// ctl.DocumentOptions.SecurityOptions.ShowPermissionTip = true;
			// ctl.DocumentOptions.SecurityOptions.TrackVisibleLevel1.DeleteLineNum = '2'; // 在痕迹视图下，删除的内容会加删除线。该设置表示删除线的条数。
			// ctl.DocumentOptions.SecurityOptions.TrackVisibleLevel1.DeleteLineColorString = '#ff0000'; // 表示删除线的颜色
			// ctl.DocumentOptions.SecurityOptions.TrackVisibleLevel1.UnderLineColorString = '#ffff00'; // 删除线的颜色
			// ctl.DocumentOptions.SecurityOptions.TrackVisibleLevel1.UnderLineColorNum = '2'; // 在痕迹视图下，书写的内容会加下划线。该设置表示下划线的条数。
			// ctl.DocumentOptions.SecurityOptions.TrackVisibleLevel1.BackgroundColorString = 'LightGrey'; // 书写或删除内容的背景颜色。
			// 创建编辑器框架
			ctl.BuildFrame(function () {
			});

			ctl.DocumentLoad = function () {
				_this.setInputValue(); // 赋值
				// console.log(param.formView)
				param && param.formView === 'Normal' ? _this.setContenteditable() : ''; // 页眉不可操作
				// var info = ctl.getServerPerformances();
				// console.log(info)
				// if (info != null) {
				// 	document.getElementById("lblServerTime").innerHTML = "|生成"
				// 		+ info.characters + "个字符，编辑器内核耗时"
				// 		+ info.serverTicks + "毫秒,服务器端耗时"
				// 		+ info.totalServerTicks + "毫秒 ，客户端耗时"
				// 		+ info.clientTicks + "毫秒。"
				// 		+ " 最大并发数:" + info.maxOnlineNumber
				// 		+ " 当前并发数:" + info.currentOnlineNumber;
				// }
				// let HDSD00_13_104 = ctl.GetContentDocument().getElementById('HDSD00.13.104')?.childNodes[1];
				// HDSD00_13_104?.classList?.add('emr-common-select');

				// 动态下拉列表
				ctl.EventQueryListItems = function (eventObject) {
					// console.log('动态下拉列表', eventObject)
					// CS做的模板跟BS做的模板不一样
					let domId = eventObject && eventObject.ListSourceName ? eventObject.ListSourceName : eventObject.ControlName;
					let num = '1';
					let obj = {};
					// console.log('动态下拉列表', _this.state.insertTemplateArr, domId)
					for (var i = 0; i < _this.state.insertTemplateArr.length; i++) {// 自定义数据
						if (domId === _this.state.insertTemplateArr[i].fieldID) {
							obj = _this.state.insertTemplateArr[i];
							num = '1'
							break;
						} else {
							for (var j = 0; j < _this.state.customDataTableData.length; j++) {// 自定义数据
								if (domId == _this.state.customDataTableData[j].code) {
									obj = _this.state.customDataTableData[j];
									num = '2'
									break;
								}
							}
						}
					}
					let currentSubDoc = ctl.CurrnetElement(function (node) {
						return (node.nodeName == 'DIV' && node.getAttribute('dctype') == 'XTextSubDocumentElement');
					})
					let recordDOMID = currentSubDoc?.id || '';
					let modalTitle = eventObject.Element && eventObject.Element.innerText ? eventObject.Element.innerText : '动态下拉选择';
					let selectRowData = { ...obj, modalTitle, recordDOMID }
					if (selectRowData && selectRowData.baseDataSet && selectRowData.baseDataSet === 'Y' && selectRowData.type !== 'DIAG') { // 判断动态下拉是否需要弹窗选择
						_this.getModalColumns(selectRowData && selectRowData.baseDataColumn ? selectRowData.baseDataColumn : '');
						_this.setState({ dropDownSearch: true, selectRowData }, () => {
							_this.handleQuery();
						})
					} else if (selectRowData && selectRowData.baseDataSet && selectRowData.baseDataSet === 'Y' && selectRowData.type === 'DIAG') { // 弹出诊断弹窗
						_this.setState({ diagnosisSearch: true, diagnosisRowData: selectRowData })
					} else {
						_this.getCustomDataValue(num, obj, eventObject);
					}
				}

				// 自定义下拉列表
				// if (ctl.EventDropdownEditor == null) {
				// 绑定控件的EventDropdownEditor事件。提供自定义的下拉列表内容。
				// ctl.EventDropdownEditor = function (args) {
				// console.log('args', args, this.value);
				// let elementID = args?.element?.id;
				// let currenttSubDoc = ctl.CurrnetElement(function (node) {
				// 	return (node.nodeName == 'DIV' && node.getAttribute('dctype') == 'XTextSubDocumentElement');
				// });
				// let recordDOMID = currenttSubDoc?.id || '';
				// // let value = ctl.GetElementTextByID(elementID, recordDOMID); // 
				// console.log('recordDOMID', elementID, recordDOMID)
				// }
				// } else {
				// 	ctl.EventDropdownEditor = null;
				// }

				// 监听右击事件
				let doc = ctl.GetContentDocument();
				doc.body.style.zoom = scaleZoom || '1';
				doc.onmouseup = function (event) {
					// console.log('右击event', event)
					var event = event || window.event;
					if (event.button == '2') {
						_this.mySetContextMenu();
					}
				};

				// 输入域change事件
				ctl.EventChangeContent = function (event) {
					let { insertTemplateArr } = _this.state;
					let recordArr = [];
					for (var i = 0; i < insertTemplateArr.length; i++) {
						if (insertTemplateArr[i].fieldID && insertTemplateArr[i].nurseRecordFlag === 'Y') {
							recordArr.push(insertTemplateArr[i].fieldID || '')
						}
					}
					let currentInput = event?.GetCurrentInputField();
					let currentFieldID = currentInput?.id || '';
					let isRecordFlag = false; // 护理记录列输入域标识
					for (var i = 0; i < recordArr.length; i++) {
						if ((recordArr[i] === currentFieldID) || (currentFieldID.indexOf(recordArr[i]) > -1)) { // 存在添加行的情况C
							isRecordFlag = true;
							break;
						}
					}
					if (isRecordFlag) { // recordArr - 护理记录单集合
						_this.handleNursingRecords(currentFieldID)
					}
					_this.handleRecordInputCopysource(currentFieldID, currentInput?.dc_innervalue || currentInput?.dc_innertext || '');
				}

				// 鼠标单击事件
				ctl.ondocumentclick = function (eventObject) {
					var node = ctl.CurrnetElement();// 获得元素的ID值
					var initID = '';
					while (node != null) {
						initID = node.id;
						if (initID != null && initID.length > 0) {
							break;
						}
						node = node.parentNode;
					}
					if (param && param.formView === 'Normal' && initID) { // 当为表单模式并且该区域为病程时
						_this.props && _this.props.getKnowledgeBaseTreeData && _this.props.getKnowledgeBaseTreeData(initID);  // 获取该病程的知识库数据
					}
					if (initID == '345') {
						var oldText = ctl.GetElementTextByID(initID);//当前文本
						_this.setState({ isShowCustomPopUps: true, initID })
						if (newText != null && newText.length > 0) {
							var result = ctl.SetElementTextByID(initID, newText);//赋值
						}
					}
					// console.log('_this.state.insertTemplateArr', _this.state.insertTemplateArr, initID)
					for (var i = 0; i < _this.state.insertTemplateArr.length; i++) {
						if (_this.state.insertTemplateArr[i].fieldID === initID && _this.state.insertTemplateArr[i].type === 'B') { // 点击病历内按钮 -> 验光单复制功能
							_this.handleBtnClick(_this.state.insertTemplateArr[i])
						}
					}
				}

				// 鼠标双击事件
				ctl.ondocumentdblclick = function (eventObject) {
					let currenttSubDoc = ctl.CurrnetElement(function (node) {
						return (node.nodeName == 'DIV' && node.getAttribute('dctype') == 'XTextSubDocumentElement');
					})
					let recordDOMID = currenttSubDoc?.id || '';
					let id = eventObject && 'path' in eventObject && Array.isArray(eventObject.path) && eventObject.path.length > 1 ? (eventObject.path[1]?.id || '') : (eventObject?.target?.id || eventObject?.target?.parentElement?.id || '');
					if (id.substring(0, 6) === 'basics' && (param.formView !== 'Normal')) { // 只有当输入框为基础字典时才可以绑定自定义数据集
						_this.showModal(id);
					} else if (id.substring(0, 7) === 'docSign') { // 医生签名
						let docName = userData && userData.userName ? userData.userName : '';
						var result = ctl.SetElementTextByID(id, docName, recordDOMID);//赋值
					}

					// 插入病程操作
					let textID = eventObject && 'path' in eventObject && Array.isArray(eventObject.path) && eventObject.path.length > 1 ? (eventObject.path[0]?.id || '') : (eventObject?.target?.id || eventObject?.target?.parentElement?.id || '');
					let currentFieldID = textID ? textID : id; // 诊断
					for (var i = 0; i < _this.state.insertTemplateArr.length; i++) {
						if ((_this.state.insertTemplateArr[i].fieldID === textID) && (_this.state.insertTemplateArr[i].type === 'T')) {
							let dblclickDOM = ctl.GetContentDocument().getElementById(textID);
							_this.handleShowCourseOfDisease({ ..._this.state.insertTemplateArr[i], recordDOMID }, dblclickDOM, '')
							break;
						}
						if ((_this.state.insertTemplateArr[i].fieldID === currentFieldID) && (_this.state.insertTemplateArr[i].type === 'DIAG')) {
							_this.setState({ diagnosisSearch: true, diagnosisRowData: { ..._this.state.insertTemplateArr[i], recordDOMID } })
							break;
						}
						// 医嘱录入
						if ((_this.state.insertTemplateArr[i].fieldID === currentFieldID) && (_this.state.insertTemplateArr[i].type === 'ORDER')) {
							_this.setState({ medicalOrderVisible: true, medicalOrderData: { ..._this.state.insertTemplateArr[i], recordDOMID } }, () => {
								_this.depAdviceRef && _this.depAdviceRef.loadData();
							})
							break;
						}
					}
				}

				// 动态下拉选择事件
				ctl.EventAfterFieldContentEdit = function (field) {
					if (field) {
						let fieldID = field.getAttribute('id');
						let nextFieldArr = _this.getNextFieldID(fieldID, 'arr', 'all');
						if (nextFieldArr && nextFieldArr.length === 1) {
							// 选择输入域
							setTimeout(() => {
								let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldArr[0]);
								ctl.FocusAdjacent('afterBegin', nextFieldDOM);
							}, 300);
						}
					}
				}

				// 键盘按下事件 当code等于Enter时则为回车操作
				ctl.ondocumentkeyup = function (keyEvent) {
					// 343为病案首页/670为验光单/831软镜处方(其他模板回车不触发)
					let templateIDArr = ['343', '670', '831'];
					if (keyEvent && (templateIDArr.indexOf(_this.state.templateID) > -1)) {
						if (keyEvent.keyCode === 13) { // 回车
							let fieldID = keyEvent.target.getAttribute('id');
							if ((fieldID && fieldID.indexOf('ComboBox') === -1) || _this.state.templateID === '670' || _this.state.templateID === '831') { // ComboBox为动态下拉
								let nextFieldArr = _this.getNextFieldID(fieldID, 'arr', 'all', keyEvent.code === 'ArrowUp' ? 'prev' : 'next');
								if (nextFieldArr && nextFieldArr.length === 1) {
									setTimeout(() => {
										let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldArr[0]);
										// console.log('nextFieldDOM', nextFieldDOM)
										// $(nextFieldDOM).focus();
										ctl.FocusAdjacent('afterBegin', nextFieldDOM);
									}, 300);
								}
							}
						}
					}
				}

				// 打印预览文件前事件
				ctl.EventBeforePrint = function (eventObject) {
					// console.log('触发了打印预览文件前事件',_this.state.basicID)
					if (_this.state.templateID === '107') { // 当加载的模板韦住院病案首页时打印时加边框线
						var style = $("<style>td[id='dcGlobalRootElement'] [dcpart='pagecontent']{border:1px solid #000}</style>")
						$(eventObject).find('head').append(style) // 2020001
					}
					if (_this.state.templateID === '343') { // 病案首页
						let hrDom = eventObject.getElementById('hl1');
						if (hrDom) {
							hrDom.style.width = '100%';
						}
					}
					let btnArr = ['newtitle', 'YGDCopyL', 'YGDCopyS']; // 新增病程，验光单复制按钮
					for (var i = 0; i < btnArr.length; i++) {
						let deleteTitleFlag = false;
						if (eventObject && eventObject.getElementById(btnArr[i])) { // 打印预览删除按钮
							deleteTitleFlag = true
							//当插入病程按钮到页脚时处理
							while (deleteTitleFlag) {
								eventObject.getElementById(btnArr[i]).remove();
								if (!eventObject.getElementById(btnArr[i])) { // 打印预览删除按钮
									deleteTitleFlag = false;
								}
							}
						}
					}

					// 合肥入院记录
					if (_this.state.userData?.hospCode === 'H03' && _this.state.templateID === '77') {
						// 补充诊断  参数二为诊断的外层包裹id，参数三为诊断输入域ID
						_this.remoteDiagnosticModule(eventObject, 'field326', 'basic100126');
						// 修订诊断 -- CS端修改模板后这两个ID会自动变更basicID
						_this.remoteDiagnosticModule(eventObject, 'field232', _this.state.basicID);
					}

					// 广州番禺病案首页线打印不全问题暂时处理方案
					if (_this.state.userData?.hospCode === 'H23' && _this.state.templateID === '343') {
						let hrDom15 = eventObject.getElementById('hl5');
						let hrDom16 = eventObject.getElementById('hl6');
						if (hrDom15 && hrDom16) {
							hrDom15.style.margin = '6px 0 0 0';
							hrDom16.style.margin = '6px 0 0 0';
						}
					}

					// 圈文字
					let dataSource = _this.state.insertTemplateArr && _this.state.insertTemplateArr.length > 0 ? JSON.parse(JSON.stringify(_this.state.insertTemplateArr)) : [];
					if (dataSource && dataSource.length > 0) {
						for (var i = 0; i < dataSource.length; i++) {
							let filedDOM = eventObject.getElementById(dataSource[i].fieldID);
							if (dataSource[i].displayTypeValue && dataSource[i].displayTypeValue === 'Y' && dataSource[i].displayTypeCode && dataSource[i].displayTypeCode === 'rectangle' && filedDOM) {
								filedDOM.style.border = '1px solid #000';
								filedDOM.style.display = 'inline-block';
								filedDOM.style.minWidth = '16px';
								filedDOM.style.maxWidth = '16px';
								filedDOM.style.width = '16px';
								filedDOM.style.minHeight = '16px';
								filedDOM.style.maxHeight = '16px';
								filedDOM.style.height = '16px';
								filedDOM.style.lineHeight = '16px';
								filedDOM.style.textAlign = 'center';
							}
						}
					}

					// 去除最后一个病程的paddingBottom样式
					var recordsArr = ctl && ctl.GetCourseRecords && ctl.GetCourseRecords();
					if (recordsArr && recordsArr.length > 0) {
						let noPagination = []; // 保存不分页的数据
						for (var j = 0; j < recordsArr.length; j++) {
							let recordsElement = eventObject.getElementById(recordsArr[j].ElementID);
							// 判断该病程是否属于强制分页的
							if (recordsArr[j].ElementID && recordsArr[j].ElementID.substring(0, 6) && recordsArr[j].ElementID.substring(0, 6) === 'paging') {
								if (recordsElement && recordsElement.style) {
									recordsElement.style.paddingBottom = 0;
								}
								continue;
							}
							noPagination.push(recordsElement);
						}
						// 不强制分页的数据将最后一个病程的paddingBottom样式去除
						if (noPagination && noPagination.length > 0 && noPagination[noPagination.length - 1] && noPagination[noPagination.length - 1].style) {
							noPagination[noPagination.length - 1].style.paddingBottom = 0;
						}
					}
				}

				// 粘贴前事件
				// ctl.EventBeforePaste = function (evBP) {
				// 	var cbData = evBP && evBP.clipboardData ? evBP.clipboardData : '';
				// 	var pasteText = cbData && cbData.getData && cbData.getData('text');
				// 	pasteText = pasteText.replace(/[\[\]]/g, ''); // C除字符串括号
				// 	pasteText = pasteText.replace(/\s+/g, ''); // 去除空格
				// 	pasteText = pasteText.replace(/<\/?.+?>/g, ''); // 去除回车
				// 	pasteText = pasteText.replace(/[\r\n]/g, ''); // 去除回车
				// 	// 删除选中的内容
				// 	ctl && ctl.DocumentSelection && ctl.DocumentSelection().deleteFromDocument && ctl.DocumentSelection().deleteFromDocument();
				// 	ctl && ctl.DCExecuteCommand && ctl.DCExecuteCommand('Spechars', false, pasteText);
				// 	return false;
				// };
				ctl.EventBeforePaste = function (evBP) {
					// if (_this.state.pasteFormat === 'Y') {
					// 	_this.setState({ pasteFormat: 'N' })
					// 	return true;
					// } else {
					var pasteText = '';
					if (evBP.clipboardData != null) {
						var cbData = evBP && evBP.clipboardData ? evBP.clipboardData : '';
						pasteText = cbData.getData('text')
					} else {
						pasteText = ctl.copyText
					}
					if (typeof (pasteText) === 'string') {
						pasteText = pasteText.replace(/[\[\]]/g, ''); // 去除字符串括号
						if (_this.props.pasteRemoveSpaces !== 'N') {
							pasteText = pasteText.replace(/\s+/g, ''); // 去除空格
						}
						pasteText = pasteText.replace(/<\/?.+?>/g, ''); // 去除回车
						pasteText = pasteText.replace(/[\r\n]/g, ''); // 去除回车
					}
					// 删除选中的内容
					ctl && ctl.DocumentSelection && ctl.DocumentSelection().deleteFromDocument && ctl.DocumentSelection().deleteFromDocument();
					ctl && ctl.DCExecuteCommand && ctl.DCExecuteCommand('Spechars', false, pasteText);
					return false;
					// }
				}
			}
		} catch (error) {
			// console.log(error)
			this.setState({ templateErrorMes: '病历模板加载失败，请重新进入该页面' });
		}
	}

	// 病程输入域关联复制
	handleRecordInputCopysource = (fieldID, inputVal) => {
		let ctl = document.getElementById(this.editorID);
		// 获取光标所在病程
		let currenttSubDoc = ctl.CurrnetElement(function (node) {
			return (node.nodeName == 'DIV' && node.getAttribute('dctype') == 'XTextSubDocumentElement');
		})
		if (this.state.courseOfDiseaseFlag === 'Y' && currenttSubDoc && currenttSubDoc.id && fieldID) {
			let reocrdID = currenttSubDoc.id;
			let doc = ctl && ctl.GetContentDocument().getElementById(reocrdID);
			let inputs = $(doc).find("[dctype='XTextInputFieldElement']"); // JQUERY
			for (let i = 0; i < inputs.length; i++) {
				let index = i;
				let currentDom = inputs[index];
				let copyFieldID = inputs.eq(index).attr('dc_copysource');
				copyFieldID = copyFieldID && copyFieldID.indexOf('SourceID:') > -1 ? copyFieldID.split('SourceID:')[1] : '';
				if (copyFieldID && copyFieldID === fieldID) {
					let value = inputVal || ctl.GetElementTextByID(fieldID, reocrdID); // 获取病程中的内容
					currentDom.firstChild.nextSibling.outerHTML = '<span>' + (value) + '</span>';
					break;
				}
			}
		}
	}

	// 病历内按钮点击事件
	handleBtnClick = (record) => {
		let ctl = document.getElementById(this.editorID);
		let copyInfo = record?.copyInfo || [];
		if (ctl && copyInfo && copyInfo.length > 0) { // 验光单复制
			for (let i = 0; i < copyInfo.length; i++) {
				let currentValue = copyInfo[i] && 'copyFrom' in copyInfo[i] && copyInfo[i].copyFrom ? ctl.GetElementTextByID(copyInfo[i].copyFrom) : ''; // 获取输入域value
				if (currentValue && copyInfo[i] && 'copyTo' in copyInfo[i] && copyInfo[i].copyTo) {
					if ('add' in copyInfo[i] && copyInfo[i].add) { // add值
						let addValue = ctl.GetElementTextByID(copyInfo[i].add);
						let formFixed = currentValue && String(currentValue).indexOf('.') > -1 ? String(currentValue).split('.')[1].length : 0;
						let addFixed = addValue && String(addValue).indexOf('.') > -1 ? String(addValue).split('.')[1].length : 0;
						currentValue = (parseFloat(currentValue) || 0) + (parseFloat(addValue) || 0);
						if (formFixed > 0 || addFixed > 0) {
							let fixed = formFixed > addFixed ? formFixed : addFixed;
							currentValue = currentValue.toFixed(fixed > 2 ? 2 : fixed); // 最多保留两位
						}
						if (currentValue && Number(currentValue) > 0) { // 大于0默认给加号
							currentValue = '+' + currentValue;
						}
					}
					ctl.SetElementTextByID(copyInfo[i].copyTo, currentValue); // 输入域赋值
				}
			}
		}
	}

	// 护理记录输入域处理 - 超过特定字数自动换行输入
	handleNursingRecords = Util.debounce((currentFieldID) => {
		const { userData, templateParams } = this.state;
		let recordsLength = templateParams?.nurseRecordsInputLength || parseInt(this.setMessage('ElectronicCaseTemplateNursingRecordsLength', 'legth', '35'));
		let ctl = document.getElementById(this.editorID);
		let inputFields = this.getNextFieldID('all', 'arr')
		let mapFieldID = currentFieldID;
		let currentRecordArr = [currentFieldID];
		let nextDateField = 3, nextRecordField = 19;
		if (userData?.hospCode === 'H23') { // 番禺护理记录新加了一列血氧饱和度(SpO2)，计算下一行需要加1
			nextRecordField = 20;
		}
		for (let i = 0; i < inputFields.length; i++) {
			let currentFieldIndex = i;
			if (inputFields[i] === mapFieldID) {
				let currentDateVal = ctl.GetElementTextByID(inputFields[currentFieldIndex + nextDateField]); // 下一行日期,修改成判断时间 modify by liangjiaquan 2023-01-17
				if (!currentDateVal) {
					mapFieldID = inputFields[currentFieldIndex + parseInt(templateParams?.nextNurseRecord || nextRecordField)]; // 下一个护理记录输入框
					currentRecordArr.push(mapFieldID);
				}
			} else {
				continue;
			}
		}
		currentRecordArr = [...new Set(currentRecordArr)].filter(item => (item !== undefined && item !== 'undefined' && item !== null && item !== 'null'));
		let currentDateRangeStr = '';
		let lastFieldVal = '';
		for (let i = 0; i < currentRecordArr.length; i++) { // 获取当前日期范围内的所有内容
			let currentRecordIndex = i;
			let currentRecordVal = ctl.GetElementTextByID(currentRecordArr[i]);
			currentRecordVal = currentRecordVal === 'null' || currentRecordVal === null || currentRecordVal === 'undefined' || currentRecordVal === undefined ? '' : currentRecordVal;
			currentDateRangeStr += currentRecordVal;
			if (currentRecordIndex === currentRecordArr.length - 1) {
				lastFieldVal = currentRecordVal;
			}
		}
		let currentDateRangeArr = Util.stringSpecifiedLengthCut(currentDateRangeStr, recordsLength, currentRecordArr?.length || 0); // 将当前日期范围内的所有内容进行分割，然后再单个set到每个输入域上
		for (let i = 0; i < currentDateRangeArr.length; i++) {
			currentDateRangeArr[i] && currentDateRangeArr[i] !== null && currentDateRangeArr[i] !== 'null' && currentDateRangeArr[i] !== undefined && currentDateRangeArr[i] !== 'undefined' && ctl && ctl.SetElementTextByID(currentRecordArr[i], currentDateRangeArr[i]);
		}
		if (!lastFieldVal) { // 判断需要跳转的光标输入域有没有值，没有值则跳转
			let focusField = ctl.GetContentDocument().getElementById(currentRecordArr[currentDateRangeArr.length - 1])
			ctl.FocusAdjacent('beforeEnd', focusField);
		}
	})

	// 删除诊断模块，根据诊断输入域，有值则不删除，没有值则删除
	remoteDiagnosticModule = (eventObject, parentNode, domID) => {
		let revisedDiagnosisChildNodes = eventObject.getElementById(domID) ? eventObject.getElementById(domID).childNodes : '';
		if (!revisedDiagnosisChildNodes && eventObject.getElementById(parentNode)) {
			let field326ParentNode = eventObject.getElementById(parentNode) && eventObject.getElementById(parentNode).parentNode ? eventObject.getElementById(parentNode).parentNode : '';
			let field326Autograph = field326ParentNode && field326ParentNode.nextSibling ? field326ParentNode.nextSibling : '';
			let field326Date = field326ParentNode && field326ParentNode.nextSibling && field326ParentNode.nextSibling.nextSibling ? field326ParentNode.nextSibling.nextSibling : '';
			field326Date && field326Date.remove();
			field326Autograph && field326Autograph.remove();
			field326ParentNode && field326ParentNode.remove();
		}
	}

	// 获取当前输入域的下一个输入域ID
	getNextFieldID = (fieldID, type, valueType, focusFlag) => {
		let fieldData = this.getMedicalRecordFileIDAndValue(valueType || fieldID);
		let nextFieldID = [];
		if (fieldData && fieldData.length > 0) {
			for (var i = 0; i < fieldData.length; i++) {
				if ((fieldData[i].fieldID === fieldID) || (fieldID === 'all')) {
					if (focusFlag === 'prev') { // 上一个输入域
						nextFieldID.push(fieldData[i - 1] && fieldData[i - 1].fieldID ? fieldData[i - 1].fieldID : fieldID);
					} else { // 默认下一个
						nextFieldID.push(fieldData[i + 1] && fieldData[i + 1].fieldID ? fieldData[i + 1].fieldID : fieldID);
					}
				}
			}
		}
		if (type === 'arr') {
			return nextFieldID
		} else {
			return nextFieldID && nextFieldID.length > 0 ? nextFieldID[0] : fieldID;
		}
	}

	// 获取自定义列表数据
	getCustomDataTableData = () => {
		let data = {
			params: [{}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: '06010043',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for (var i = 0; i < res.result.length; i++) {
						res.result[i].key = i;
					}
					this.setState({ customDataTableData: res.result })
				}
			}
		})
	}

	jqAjax = (flag, othCode, success, error) => {
		let url = httpConfig.ipDeault + httpConfig.urlAddress;
		let json = {
			params: [{
				ID: flag === '2' ? othCode.ID : undefined
			}]
		}
		let formData = Object.assign({}, json);
		let { userData } = window.sessionStorage
		formData.code = flag === '2' ? '06010044' : othCode.serviceCode;
		if (userData) {
			let user = JSON.parse(userData)
			let ip = React.$getSessionData('ipConfig');
			formData.session = [{
				'userID': user.userID || '',
				'locID': user.locID || '',
				'groupID': user.groupID || '',
				'hospID': user.hospID || '',
				'sessionID': user.sessionID || '',
				'hostName': ip?.hostName || '',
				'ipv4': ip?.ipv4 || '',
				'ipv6': ip?.ipv6 || '',
				'mac': ip?.mac || '',
			}]
		}
		$.ajax({
			type: 'post',                          //请求方式
			url,     //请求地址
			data: JSON.stringify(formData),                         //发送的数据，这里是json对象
			dataType: 'json',                      //数据类型
			// contentType: 'application/json;charset=utf-8',
			async: false,
			success: function (data) {
				success && success(data);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				error && error(errorThrown);
			},
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'Authorization': httpConfig.authorizationToken,
				'Access-Control-Allow-Origin': httpConfig.ipDeault
			},
		});
	}

	/*
		setElementTextByID（根据ID附上对映的值）
			path: 模板路径
			data：模板数据
			isOperable：是否可操作
			bool：弃用
			patSex：性别
			versionID：模板版本号
			templateID：模板ID
			progressID：病程记录ID（如果加载的是首程中的某一个病程）
			needUpdateData：待更新数据
			basicID:修订诊断输入域ID
	*/
	setElementTextByID = (path, data, isOperable, bool, patSex, templateParams, templateID, progressID, needUpdateData, existFieldValIDData, basicID) => {
		var ctl = document.getElementById(this.editorID);
		let { forceUnlock } = this.state;
		let params = this.props.param ? this.props.param : {};
		if (!(ctl && ctl.GetContentDocument)) {
			initCtl++
			if (initCtl < 10) {
				setTimeout(() => {
					this.setElementTextByID(path, data, isOperable, bool, patSex, templateParams, templateID, progressID, needUpdateData, existFieldValIDData, basicID)
				}, 300);
			}
			return;
		}
		// 如果点击加载的为病程并且当前加载的为首程或者为病程则不需要更新别的数据，只需要重新渲染当前模板，如果为强制解锁则需要重新加载
		if (progressID && this.state.progressID && forceUnlock !== 'Y') {
			// 如果当前加载为首程并且为阅读模式则走病程定位
			this.setState({ progressID }, () => {
				// console.log('this.state.isModifyPermissions', this.state.isModifyPermissions, params.isDelete)
				if (params.isDelete) {
					this.handleAnchorPositioning(progressID);
				} else {
					this.AjaxLoad(path, false, '', '', true); // 加载文件
				}
			})
			initCtl = 0; // 重置初始值
			return;
		}
		// 病程标志
		let courseOfDiseaseFlag = 'N';
		if (data && Array.isArray(data) && data.length > 0) {
			for (let i = 0; i < data.length; i++) {
				if (data[i].fieldID === 'newtitle' && data[i].type === 'T') {
					courseOfDiseaseFlag = 'Y';
					break;
				}
			}
		}
		let templateParamsObj = templateParams && Object.prototype.toString.call(templateParams) === '[object Object]' ? templateParams : {};
		this.setState({
			forcedPageChange: parseInt(templateID) === 717 ? true : false, // 插入的病程是否单独页打印【角塑病历】
			insertTemplateArr: data,
			isOperable,
			templateParams: templateParamsObj, // 当前加载的病历参数
			versionID: templateParamsObj?.releaseVersion || templateParams,
			templateID,
			printSpecifiedPage: [],
			isModifyPermissions: 'N',
			basicID,
			contentChangeTableData: needUpdateData, isPrintPreview: 'N', progressID, forceUnlock: 'N', IDCollection: existFieldValIDData, courseOfDiseaseFlag
		}, () => {
			initCtl = 0; // 重置初始值
			this.AjaxLoad(path, false); // 加载文件
			let contentChangeSelectedRowKeys = []; // 默认有更新数据全部勾选
			if (this.state.contentChangeTableData && this.state.contentChangeTableData.length > 0) {
				for (var i = 0; i < this.state.contentChangeTableData.length; i++) {
					contentChangeSelectedRowKeys.push(this.state.contentChangeTableData[i].key)
				}
			}
			setTimeout(() => {
				this.setState({ contentChangSelectedRows: this.state.contentChangeTableData, contentChangeSelectedRowKeys })
			}, 500)
		})
	}

	// 将页眉设置为不可编辑
	setContenteditable = () => {
		// const { insertTemplateArr } = this.state;
		let ctl = document.getElementById(this.editorID);
		let doc = ctl?.GetContentDocument();
		$(doc).find("[dctype=\"XTextDocumentHeaderElement\"],[dctype=\"XTextDocumentFooterElement\"]").attr("contenteditable", false);
		// 输入域框可见
		let inputs = $(doc).find("[dctype='XTextInputFieldElement']"); // JQUERY
		for (let i = 0; i < inputs.length; i++) {
			inputs[i].setAttribute('dc_bordervisible', 'Visible'); // 输入框是否可见，由于版本问题，模板那边有些输入域设置了不可见，前端统一处理为可见！
		}
	}

	// 动态下拉框不可编辑只能选择
	setUserEditable = (ele) => {
		let ctl = document.getElementById(this.editorID);
		let options = {
			ContentReadonly: false,
			UserEditable: false,
		}
		ctl.SetElementProperties(ele, options);
	}

	setInputValue = () => {
		var ctl = document.getElementById(this.editorID);
		if (ctl && ctl.SetElementTextByID) {
			const recordsArr = ctl && ctl.GetCourseRecords && ctl.GetCourseRecords();
			let arr = this.state.insertTemplateArr && this.state.insertTemplateArr.length > 0 ? this.state.insertTemplateArr : [];
			for (var i = 0; i < arr.length; i++) {
				let displayValue = arr[i]?.displayValue || '';
				let fieldID = arr[i]?.fieldID || '';
				let recordID = arr[i]?.recordID || '';
				if (arr[i] && fieldID && arr[i].updateFlag === 'Y' && displayValue !== undefined && displayValue !== '') {
					if (fieldID && (fieldID.slice(0, 5) === 'table')) { // 表格渲染
						this.handleTableAssignment(fieldID, displayValue);
						continue;
					} else if (fieldID && (fieldID.slice(0, 8) === 'radioBox' || fieldID.slice(0, 8) === 'checkbox')) { // 单选框/多选设置默认值
						ctl.SetElementCheckedByID(fieldID, displayValue === 'Y' ? true : false);
						continue;
					} else {
						if (recordID && recordsArr && recordsArr.length > 0) {
							for (let j = 0; j < recordsArr.length; j++) {
								let currentElementID = recordsArr[j] && recordsArr[j].ElementID ? recordsArr[j].ElementID : '';
								currentElementID = currentElementID.indexOf('record') > -1 || currentElementID.indexOf('paging') > -1 ? currentElementID.slice(6) : currentElementID;
								if (currentElementID && currentElementID === recordID) {
									ctl.SetElementTextByID(fieldID, displayValue, recordsArr[j].ElementID);
									break;
								}
							}
						} else {
							ctl.SetElementTextByID(fieldID, displayValue);
							continue;
						}
					}
				}
			}
			// if (isChangeBarcode) { // 加载条形码
			setTimeout(() => {
				this.changeBarcode();
			}, 300)
			// }
		}
	}

	// 新知识库赋值
	knowledgeBaseAssignment = (fieldID, value) => {
		var ctl = document.getElementById(this.editorID);
		if (ctl && ctl.DCExecuteCommand) {
			let result = ctl.DCExecuteCommand('Spechars', false, value); // 根据光标所在位置插入选中的知识库
			console.log(result)
		}
	}

	// 表格赋值测试
	handleTableAssignment = (tableID, tableData) => {
		// 判断传入的表格数据是否为数组
		let tableDataArr = Object.prototype.toString.call(tableData) === '[object Array]' ? tableData : [];
		let tableDataJSON = JSON.parse(JSON.stringify(tableDataArr));
		var ctl = document.getElementById(this.editorID);
		// var doc = document.getElementById(tableID).GetContentDocument();
		// var inputs = $(doc).find("[dctype='XTextInputFieldElement']");//JQUERY

		if (ctl) {
			var tableDom = ctl.GetContentDocument().getElementById(tableID); //
			let trDom = tableDom && tableDom.getElementsByTagName('tr');
			let allDOMData = [];
			if (trDom && trDom.length > 0) {
				for (var i = 0; i < trDom.length; i++) {
					let tdData = [];
					let tdDom = trDom[i].childNodes;
					for (var j = 0; j < tdDom.length; j++) {
						if (tdDom[j].childNodes && tdDom[j].childNodes.length > 0) {
							// console.log(tdDom[j].childNodes[0])
							if (tdDom[j].childNodes[0].childNodes[0] && tdDom[j].childNodes[0].childNodes[0].id) {
								tdData.push(tdDom[j].childNodes[0].childNodes[0].id)
							} else if (tdDom[j].childNodes[0].childNodes[1] && tdDom[j].childNodes[0].childNodes[1].id) {
								tdData.push(tdDom[j].childNodes[0].childNodes[1].id)
							}
						} else {
							tdData.push('')
						}
					}
					let isPush = false
					for (var k = 0; k < tdData.length; k++) {
						if (tdData[k]) {
							isPush = true;
						}
					}
					if (isPush) {
						allDOMData.push(tdData)
					}
				}
			}
			if (tableDataJSON && tableDataJSON.length > 0 && allDOMData && allDOMData.length > 0) {
				for (var i = 0; i < tableDataJSON.length; i++) {
					let oldData = tableDataJSON[i];
					let oldI = i;
					for (var j = 0; j < oldData.length; j++) {
						if (oldData[j] && allDOMData[oldI] && allDOMData[oldI][j]) {
							ctl.SetElementTextByID(allDOMData[oldI][j], oldData[j]);
						}
					}
				}
			}
		}
	}

	// 获取自定义数据值
	getCustomDataValue = (flag, othCode, eventObject) => {
		this.jqAjax(flag, othCode, (res) => { // 成功的回调
			let arr = res && res.result && res.result.length > 0 ? JSON.parse(JSON.stringify(res.result)) : [];
			arr && arr.map((item => {
				return eventObject.AddResultItemByTextValue(item.descripts, item.ID);
			}))
		}, (error) => {
			console.log(error)
		})
	}

	// 新建
	NewFile = () => {
		// 清空操作数据
		this.setState({ counterObj: {}, insertTemplateArr: [], isOperable: 'N', ajaxLoadCount: 0 });
		this.AjaxLoad("FileTemplate\\XYSTemplate\\mzdefault.xml", true);
	}

	// 重置为不可操作状态
	operableShow = (isNo) => {
		if (isNo === 'no') {
			this.setState({ isOperable: 'Y' });
		} else {
			this.setState({ counterObj: {}, insertTemplateArr: [], isOperable: 'Y' });
		}
	}

	// 服务端加载文档
	AjaxLoad = (fileName, isClear, isSave, flag, validate) => {
		let _this = this;
		try {
			var ctl = document.getElementById(this.editorID);
			let params = this.props.param ? this.props.param : {};
			ctl.preserveScrollPosition = true; // 加载文档时尽量保留页面滚动位置。
			// 文档加载后事件处理，由于采用AJAX模式，并不确定LoadDocumentFormFile()返回后是否会触发这个事件
			// 因此需要在并不确定LoadDocumentFormFile()函数前设置好这个事件处理代码。

			let result = '';
			if (_this.state.loadXMLStr) {
				_this.handleLoadXML(_this.state.loadXMLStr);
			} else {
				result = ctl.LoadDocumentFromFile(fileName, null);
			}
			console.log('服务端加载文档', result, 'ajaxLoadCount: ', _this.state.ajaxLoadCount)
			if (_this.state.ajaxLoadCount > 3) {
				message.error(`加载文件 ${fileName} 失败。`);
				_this.setState({ ajaxLoadCount: 0 })
				return;
			} else {
				setTimeout(() => {
					if (_this.state.isModifyPermissions === 'Y' || !params.isDelete) { // 编辑模式：NormalHtmlEditable，打印预览模式：PagePreviewHtml。
						if (validate == true) {
							_this.MyDocumentValueValidate();
							_this.readingAndWritingControlOfDiseaseCourse('write'); // 病程读写控制
						}
					} else {
						if (_this.handleDetermineTemplateContent() !== 'Y') {
							params?.viewEMRFlag !== 'Y' && _this.OpenPreview('noPrintPreview'); // 查看界面不直接打印预览
							_this.readingAndWritingControlOfDiseaseCourse(); // 病程读写控制
						} else {
							_this.setState({ ajaxLoadCount: _this.state.ajaxLoadCount + 1 }, () => {
								setTimeout(() => {
									_this.AjaxLoad(fileName, isClear, isSave, flag, validate);
								}, 1000)
							});
							return;
						}
					}
					_this.setState({ fileName, isClear, ajaxLoadCount: 0 }, () => {
						setTimeout(() => {
							!_this.state.isClear ? _this.clearLoadCache(_this.state.fileName) : ''; // 清除加载的版本
							if (_this.state.isModifyPermissions === 'Y' || !params.isDelete) {  // 编辑模式：NormalHtmlEditable，打印预览模式：PagePreviewHtml。
								let pageNum = ctl && ctl.GetDocumentPageNum && ctl.GetDocumentPageNum(); // 获取病历模板总页数
								_this.setState({ pageNum });
							}
						}, 500)
					})

					if (isSave === 'save') {
						setTimeout(() => {
							_this.props.handleSave('noMes')
						}, 300)
					}

					if (flag === 'template') {
						setTimeout(() => {
							_this.addCourseDiseaseStyle()
						}, 300)
					}
				}, 500)
			}
		} catch (error) {
			// this.setState({ templateErrorMes: '病历模板加载失败，请重新加载' });
			// 病历模板加载失败，请重新加载
			this.handleOnReload();
		}
	}

	// 3.3.22.清除模板版本加载缓存
	clearLoadCache = (fileName) => {
		if (!fileName) return;
		let data = {
			params: [{
				patch: fileName
			}]
		}
		$http.post('urlS', this, {
			code: '06020026',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log('清除缓存成功')
				}
			}
		})
	}

	// 编辑
	handleCompile = num => {
		var ctl = document.getElementById(this.editorID);
		switch (num) {
			case 1:
				ctl.Undo(); // 撤销
				break;
			case 2:
				ctl.Redo(); // 重做
				break;
			case 3:
				ctl.DCExecuteCommand('Copy', true, null); // 复制
				break;
			case 4:
				ctl.DCExecuteCommand('Cut', true, null); // 剪切
				break;
			case 5:
				ctl.DCExecuteCommand('Paste', true, null); // 粘贴
				break;
			case 6:
				ctl.BeginFormatBrush(); // 格式刷
				break;
			case 7:
				message.info('全选操作和常用的富文本编辑中的全选操作相同，快捷键是Ctrl+A。')
				break;
			case 8:
				ctl.DCExecuteCommand('ToupperCase', true, null); // 字母转成大写
				break;
			case 9:
				ctl.DCExecuteCommand('TolowerCase', true, null); // 字母转成小写
				break;
			default:
				message.info('删除操作和常用的富文本编辑中的删除操作相同，快捷键是Delete或BackSpace。')
		}
	}

	// 字体格式
	handleFont = num => {
		var ctl = document.getElementById(this.editorID);
		switch (num) {
			case 1:
				ctl.DCExecuteCommand('FontName', true, this.state.fontTyle)
				break;
			case 2:
				break;
			case 3:
				ctl.DCExecuteCommand('Removeformat', false, null);
				break;
			case 4:
				ctl.DCExecuteCommand('Removefontsize', true, null);
				break;
			case 5:
				ctl.DCExecuteCommand('Bold', true, null);
				break;
			case 6:
				ctl.DCExecuteCommand('Italic', true, null);
				break;
			case 7:
				ctl.DCExecuteCommand('Underline', true, null);
				break;
			case 8:
				ctl.DCExecuteCommand('Strikethrough', true, null);
				break;
			case 9:
				ctl.DCExecuteCommand('Fontborder', true, null);
				break;
			case 10:
				ctl.DCExecuteCommand('Color', true, this.state.fontColor);
				break;
			case 11:
				ctl.DCExecuteCommand('BackColor', true, this.state.fontColor);
				break;
			case 12:
				ctl.DCExecuteCommand('Superscript', true, null);
				break;
			default:
				ctl.DCExecuteCommand('Subscript', true, null);
		}
	}

	// 8.5.30.行缩进
	Indent = (num) => {
		var ctl = document.getElementById(this.editorID);
		switch (num) {
			case 1:
				ctl.DCExecuteCommand('Justifyleft', true, null);
				break;
			case 2:
				ctl.DCExecuteCommand('AlignCenter', true, null);
				break;
			case 3:
				ctl.DCExecuteCommand('AlignRight', true, null);
				break;
			case 4:
				ctl.DCExecuteCommand('Indent', true, null);
				break;
			case 5:
				ctl.DCExecuteCommand('Insertorderedlist', true, null);
				break;
			case 6:
				ctl.DCExecuteCommand('Insertunorderedlist', true, null);
				break;
			case 7:
				ctl.DCExecuteCommand('lineheight', true, 2);
				break;
			case 8:
				ctl.DCExecuteCommand('rowspacing', true, '10,top');
				break;
			case 9:
				ctl.DCExecuteCommand('rowspacing', true, '10,bottom');
				break;
			default:
				ctl.DCExecuteCommand('removeformat', true, null);
		}
	}

	// 字体格式
	handleFontType = e => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('FontName', true, e);
		this.setState({ fontTyle: undefined });
	}

	// 设置字体大小
	setFontSize = e => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Fontsize', true, e);
		this.setState({ fontSize: undefined });
	}

	scaleEditorPage = (scale = 1) => {
		const ctl = document.getElementById(this.editorID);
		const doc = ctl.GetContentDocument();
		doc.body.style.zoom = scale;
		this.setState({ scaleZoom: scale }, () => {
			React.$setLocalStorageData('ElectronicCaseTemplate_zoom', scale === '1' ? '' : scale, false); // 正常不默认展示
		})
	}

	handleShowColorTemplate = (id) => {
		let top = document.getElementById(id).getBoundingClientRect().top + 22 + 'px';
		let left = document.getElementById(id).getBoundingClientRect().left + 'px';
		this.setState({ top, left, isColorPickup: true, colorTemplateFlag: id })
	}

	cancelColorPickup = () => {
		this.setState({ isColorPickup: false });
	}

	handleColorChange = (colorCode) => {
		this.setState({ fontColor: colorCode.hex }, () => {
			if (this.state.colorTemplateFlag === (this.editorID + "font-color-icon")) {
				this.handleFont(10)
			} else {
				this.handleFont(11)
			}
			// this.cancelColorPickup();
		})
	}

	documentSetRef = ref => {
		this.documentSetChild = ref;
	}

	// 页面设置
	documentSizeSettings = () => {
		this.documentSetChild.showModal();
	}


	// 原始尺寸  自适应
	original = (AutoZoom) => {
		this.handleInit(AutoZoom)
		this.props.handleReload()
	}

	///添加行
	addRow = () => {
		// 默认为空（不复制文档内容），需要带出来数据需要设置表格行属性（复制模式：复制文档内容但清空输入域）
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Table_InsertRowDown', false, null);
	}

	// 点击打印前判断病历是否修改，已修改则先保存
	handleSaveBeforePrinting = (fn) => {
		let { isModifyPermissions } = this.state;
		let params = this.props.param ? this.props.param : {};
		let isModify = this.getModified();
		if (isModify || (!(isModifyPermissions === "N" && params.isDelete) && this.props?.saveBeforePrintingFlag === 'Y')) { // 打印前是否保存标志 - 为Y的话不管有没有修改都保存【暂时检测打印出来病历和实际保存记录对不上问题】
			let record = {
				saveType: 'print'
			};
			this.props.handleSave('saveBeforePrinting', record, fn)
		} else { // 直接打印
			console.log('直接打印',)
			fn && fn();
		}
	}

	// 打印文档
	PrintDocument = () => {
		var ctl = document.getElementById(this.editorID);
		let { printSpecifiedPage, readNum } = this.state;
		if (printSpecifiedPage && printSpecifiedPage.length > 0) {
			if (+readNum === 2) {
				message.error("预览模式下暂不支持打印指定页，请在书写模式下进行操作。");
				return;
			}
			var setting = {
				PageIndexs: printSpecifiedPage.sort().join(",")
			};
			ctl.PrintDocument(setting);
		} else {
			ctl.PrintDocument();
		}
	}

	//关闭打印预览
	ClosePrintPreview = () => {
		var ctl = document.getElementById(this.editorID);
		let chkJumpPrintID = this.editorID + 'chkJumpPrint';
		ctl.ToolbarForPrintPreview = null;
		ctl.ClosePrintPreview();
		setTimeout(() => {
			this.setState({ readNum: 1, isPrintPreview: 'N' }, () => {
				this.handleJumpPrint(false);
				if (document.getElementById(chkJumpPrintID)) {
					document.getElementById(chkJumpPrintID).checked = false;
				}
			})
		}, 100)
	}

	//设置在预览中，使用鼠标滚轮拖拽
	handleSetMouseDragScroll = (setValue) => {
		var ctl = document.getElementById(this.editorID);
		ctl.setMouseDragScrollMode(setValue);
	}

	//设置续打
	handleJumpPrint = (setValue, isClear) => {
		var ctl = document.getElementById(this.editorID);
		ctl.SetJumpPrintMode(setValue);
		let chkMouseDragScrollID = this.editorID + 'chkMouseDragScroll';
		if (document.getElementById(chkMouseDragScrollID)) {
			document.getElementById(chkMouseDragScrollID).checked = false;
		}
		ctl.setMouseDragScrollMode(false);
		let chkBoundsSelectionID = this.editorID + 'chkBoundsSelection';
		if (document.getElementById(chkBoundsSelectionID)) {
			document.getElementById(chkBoundsSelectionID).checked = false;
		}
		ctl.SetBoundsSelectionViewMode(false);
		if (isClear !== 'N') {
			this.setState({ printSpecifiedPage: [] })
		}
	}

	// 区域选择打印
	handleBoundsSelection = (val) => {
		var ctl = document.getElementById(this.editorID);
		ctl.SetBoundsSelectionViewMode(val);
		let chkJumpPrintID = this.editorID + 'chkJumpPrint';
		let chkMouseDragScrollID = this.editorID + 'chkMouseDragScroll';
		if (document.getElementById(chkJumpPrintID)) {
			document.getElementById(chkJumpPrintID).checked = false;
		}
		if (document.getElementById(chkMouseDragScrollID)) {
			document.getElementById(chkMouseDragScrollID).checked = false;
		}
		ctl.SetJumpPrintMode(false);
		ctl.setMouseDragScrollMode(false);
	}

	// 获取输入域 --- 过滤删除的元素
	getInputField = () => {
		let { insertTemplateArr } = this.state;
		let arr = [];
		if (!(insertTemplateArr && insertTemplateArr.length > 0)) {
			return arr;
		}
		var ctl = document.getElementById(this.editorID);
		var doc = ctl.GetContentDocument();
		var inputs = $(doc).find("[dctype='XTextInputFieldElement']");//JQUERY
		var fieldList = [];
		for (var i = 0; i < inputs.length; i++) {
			fieldList.push(inputs.eq(i).attr("id"))
		}
		for (var i = 0; i < insertTemplateArr.length; i++) {
			for (var j = 0; j < fieldList.length; j++) {
				if (insertTemplateArr[i].fieldID === fieldList[j]) {
					arr.push(insertTemplateArr[i])
				}
			}
		}
		return arr;
	}

	// 内容校验
	MyDocumentValueValidate = (show) => {
		try {
			var result = document.getElementById(this.editorID).DCExecuteCommand("DocumentValueValidate", false, null);
			if (result != null && result.length > 0) {
				var errorList = [];
				for (var iCount = 0; iCount < result.length; iCount++) {
					var item = result[iCount];
					var opt = document.createElement("option");
					opt.result = item;
					opt.appendChild(document.createTextNode((iCount + 1) + " |" + item.ElementID + " " + item.Message));
					if (show == "true") {
						var fileName = '';
						if (item.Element.attributes.name) {
							fileName = item.Element.attributes.name.nodeValue;
						} else {
							fileName = item.ElementID;
						}
						errorList.push(<div style={{ display: 'flex' }}>{fileName}：&nbsp;&nbsp;<div style={{ color: 'red' }}>{item.Message}</div></div>)
						//message.error(fileName + " " + item.Message);
					}
				}
				if (errorList.length > 0) {
					confirm({
						title: '提示,存在以下错误信息，请完善后再保存!',
						content: (<div>{errorList}</div>),
						okText: '知道了',
						width: '600px',
						cancelButtonProps: {
							style: {
								display: 'none'
							}
						},
						onOk() {

						}
					});
				}
				return show == "true" ? false : true;
			} else {
				return true
			}
		} catch (error) {
			console.log(error);
			return true;
		}
	}

	// 获取模板xml
	getTemplateXml = (flag) => {
		var ctl = document.getElementById(this.editorID);
		let status = false;
		let allRecordID = this.GetCourseRecordXML(); // 获取所有病程ID
		if (!ctl) {
			return;
		}
		if (flag === 'form') { // 表单模式需要走验证
			status = this.MyDocumentValueValidate('true');
		} else if (flag === 'release') { // 模板发布时去除病程样式
			this.clearCourseDiseaseStyle();
		} else if (flag == 'allRecordID') { // 返回病程ID
			return allRecordID
		}
		var xmlStr = ctl.SaveDocumentToString('XML');
		let dataSource = this.getInputField();
		let recordDataSource = this.GetCourseRecordXML('inputArr');
		let obj = {
			xmlStr,
			dataSource,
			status,
			allRecordID,
			recordDataSource,
			isEmptyTemplate: this.handleDetermineTemplateContent()
		}
		return obj;
	}

	// 通用公式
	MyInsertMedicalExpression1 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression1',
			'ExpressionStyle': 'FourValues1',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 月经史公式1
	MyInsertMedicalExpression2 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression2',
			'ExpressionStyle': 'FourValues2',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options)
	}

	// 月经史公式2
	MyInsertMedicalExpression3 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression3',
			'ExpressionStyle': 'ThreeValues',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 月经史公式3
	MyInsertMedicalExpression4 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression4',
			'ExpressionStyle': 'FourValues',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 瞳孔图公式
	MyInsertMedicalExpression5 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression5',
			'ExpressionStyle': 'Pupil',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14;Value5:14;Value6:14;Value7:14;'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 光定位图公式
	MyInsertMedicalExpression6 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression6',
			'ExpressionStyle': 'LightPositioning',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14;Value5:14;Value6:14;Value7:14;Value8:14;Value9:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 胎心图公式
	MyInsertMedicalExpression7 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression7',
			'ExpressionStyle': 'FetalHeart',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14;Value5:14;Value6:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 标尺公式
	MyInsertMedicalExpression8 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression8',
			'ExpressionStyle': 'PainIndex',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 恒牙牙位图公式
	MyInsertMedicalExpression9 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression9',
			'ExpressionStyle': 'PermanentTeethBitmap',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:14;Value3:14;Value4:14;Value5:14;Value6:14;Value7:14;Value8:14;Value9:14;Value10:14;Value11:14;Value12:14;Value13:14;Value14:14;Value15:14;Value16:14;Value17:14;Value18:14;Value19:14;Value20:14;Value21:14;Value22:14;Value23:14;Value24:14;Value25:14;Value26:14;Value27:14;Value28:14;Value29:14;Value30:14;Value31:14;Value32:14'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 乳牙牙位图公式
	MyInsertMedicalExpression10 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression10',
			'ExpressionStyle': 'DeciduousTeech',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:Ⅴ;Value2:Ⅳ;Value3:Ⅲ;Value4:Ⅱ;Value5:Ⅰ;Value6:Ⅰ;Value7:Ⅱ;Value8:Ⅲ;Value9:Ⅳ;Value10:Ⅴ;Value11:Ⅴ;Value12:Ⅳ;Value13:Ⅲ;Value14:Ⅱ;Value15:Ⅰ;Value16:Ⅰ;Value17:Ⅱ;Value18:Ⅲ;Value19:Ⅳ;Value20:Ⅴ'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 分数公式
	MyInsertMedicalExpression11 = () => {
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'expression11',
			'ExpressionStyle': 'Fraction',
			'Type': 'XTextNewMedicalExpressionElement',
			'FontSize': '12',
			'Width': '112px',
			'Height': '46px',
			'Values': 'Value1:14;Value2:7'
		};
		ctl.DCExecuteCommand('insertmedicalexpression', false, options);
	}

	// 插入超链接
	MyLink = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Link', true, 'http://www.baidu.com/');
	}

	// 断开超链接
	Unlink = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Unlink', false, null);
	}

	// 插入当前时间
	MyTime = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Time', false, null);
	}

	// 插入特殊字符 ---- 可以插入一段自己定义的字符串
	Spechars = (str, quoteArr) => {
		if (quoteArr && Array.isArray(quoteArr) && quoteArr.length > 0) { // 护 理 记 录 单 
			this.handleVitalSignReference(quoteArr);
		} else {
			var ctl = document.getElementById(this.editorID);
			ctl.DCExecuteCommand('Spechars', false, str);
		}
	}

	// 生命体征引用 - 护理记录单单独处理
	handleVitalSignReference = (quoteArr) => {
		const { userData } = this.state;
		var ctl = document.getElementById(this.editorID);
		var currentFieldID = ctl.CurrentInputField()?.id || ''; // 获取当前光标所在的输入域
		if (!currentFieldID) {
			message.info('请将光标定位到需引用行任意一个输入域！');
			return;
		}
		let rowCount = 19;
		if (userData?.hospCode === 'H23') { // 番禺护理记录新加了一列血氧饱和度(SpO2)，计算下一行需要加1
			rowCount = 20;
		}
		let inputFields = Util.cutArray(this.getNextFieldID('all', 'arr').slice(5), rowCount); // 截取前面的五个
		let recordFieldIDArr = [];
		for (var i = 0; i < inputFields.length; i++) {
			if (inputFields[i].indexOf(currentFieldID) > -1) {
				recordFieldIDArr = inputFields[i];
				break;
			}
		}
		for (let i = 0; i < quoteArr.length; i++) { // 输入域赋值
			quoteArr[i] && quoteArr[i] !== null && quoteArr[i] !== 'null' && ctl && ctl.SetElementTextByID(recordFieldIDArr[i], quoteArr[i]);
		}
	}

	// 8.5.61.拆分成行
	Splittorows() {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('splittorows', false, null);
	}

	// 拆分成列
	Splittocols() {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('splittocols', false, null);
	}

	// 插入input
	InsertDynamicList = (record) => {
		let { insertTemplateArr, counterObj } = this.state;
		let obj = JSON.parse(JSON.stringify(record))
		counterObj[obj.code] = counterObj[obj.code] ? counterObj[obj.code] + 1 : 1;
		obj.fieldID = obj.code + counterObj[obj.code];
		insertTemplateArr.push(obj);
		this.setState({ insertTemplateArr, counterObj }, () => {
			var ctl = document.getElementById(this.editorID);
			var options = {
				'ContentReadonly': false,
				'ToolTip': obj.descripts,
				'BackgroundText': obj.descripts,
				// 'SpecifyWidth': 1,
				'Text': '',
				'InnerValue': '',
				'ID': obj.fieldID,
				'StartBorderText': '[',
				'EndBorderText': ']',
				'Name': 'input'
			};
			var field = ctl.DCExecuteCommand('InsertInputField', true, options);
			if (field != null) {
				ctl.FocusAdjacent('afterEnd', field); //这里的第一个参数可以是beforeBegin,afterBegin,beforeEnd,afterEnd
			}
		})
	}

	// 打印预览
	OpenPreview = (type) => {
		//获得最外面的容器元素并设置位置
		const { progressID } = this.state;
		var ctl = document.getElementById(this.editorID);
		if (type === 'noPrintPreview') { // 查看模式，加载已写过的病历
			ctl && ctl.ToolbarForPrintPreview ? ctl.ToolbarForPrintPreview = null : '';
			ctl && ctl.LoadPrintPreview && ctl.LoadPrintPreview();
			setTimeout(() => {
				progressID && this.handleAnchorPositioning(progressID)
			}, 800)
		} else {
			ctl.ToolbarForPrintPreview = document.getElementById(this.editorID + 'btrPrintPreview');
			this.setState({ isPrintPreview: 'Y', printSpecifiedPage: [] }, () => {
				//填充打印预览内容
				ctl && ctl.LoadPrintPreviewWithPermissionMark && ctl.LoadPrintPreviewWithPermissionMark();
			})
		}
	}

	// 光标位置
	cursorPosition = (ID) => {
		var ctl = document.getElementById(this.editorID);
		var field = ctl.GetContentDocument().getElementById('dctable_AllContent');
		ctl.GetContentContainer().focus();
		ctl.FocusAdjacent('afterEnd', field);
	}

	// 获取被选中的XMl
	getSelectXML = () => {
		let xml = document.getElementById(this.editorID).SelectionXml();
		this.setState({ selectionXml: xml })
	}

	// 插入输入域
	insertInputField = (num) => {
		var ctl = document.getElementById(this.editorID);
		let options = {}
		let { counterObj, insertTemplateArr } = this.state;
		if (num === 1) {
			counterObj.txtAge = counterObj && counterObj.txtAge ? counterObj.txtAge + 1 : 1;
			options = {
				'ContentReadonly': false,
				'ToolTip': '请输入年龄',
				'BackgroundText': '请输入年龄',
				'Text': '30',
				'InnerValue': '30',
				'ValidateStyle': 'Required:True;ValueType:Numeric;CheckMaxValue:True;MaxValue:150;CheckMinValue:True;MinValue:0',
				'EnableValueValidate': true,
				'Name': '年龄',
				'ID': 'txtAge' + counterObj.txtAge,
				'StartBorderText': '【',
				'EndBorderText': '】',
				'UnitText': '岁'
			};
		} else if (num === 2) {
			counterObj.txtDate = counterObj && counterObj.txtDate ? counterObj.txtDate + 1 : 1;
			options = {
				'ContentReadonly': false,
				'ToolTip': '请输入日期',
				'BackgroundText': '请输入日期',
				'Text': '2015-01-09 09:39',
				'InnerEditStyle': 'DateTime',
				'EditorActiveMode': 'MouseClick',
				'EnableValueValidate': true,
				'Name': '日期',
				'ID': 'txtDate' + counterObj.txtDate
			};
		} else if (num === 3) {
			counterObj.txtInput = counterObj && counterObj.txtInput ? counterObj.txtInput + 1 : 1;
			options = {
				'ContentReadonly': false,
				'dc_deleteable': 'false',
				'ToolTip': '请输入',
				'BackgroundText': '请输入',
				'SpecifyWidth': 5,
				'Text': '',
				'InnerValue': '',
				'Name': '请输入',
				'ID': 'txtInput' + counterObj.txtInput,
				// 'ValidateStyle': 'Required:True;ValueType:Numeric;CheckMaxValue:True;MaxValue:150;CheckMinValue:True;MinValue:0',
				// 'EnableValueValidate': true,
				'StartBorderText': '[',
				'EndBorderText': ']'
			};
		}
		var field = ctl.DCExecuteCommand('InsertInputField', true, options);
		if (field != null) {
			ctl.FocusAdjacent('afterEnd', field); //这里的第一个参数可以是beforeBegin,afterBegin,beforeEnd,afterEnd
		}
		insertTemplateArr.push(options)
		this.setState({ counterObj, insertTemplateArr })
	}

	// 插入按钮
	MyInsertButtonInputField = () => {
		let { counterObj, insertTemplateArr } = this.state;
		counterObj.button = counterObj && counterObj.button ? counterObj.button + 1 : 1;
		var ctl = document.getElementById(this.editorID);
		var options = {
			'ID': 'button' + counterObj.button,
			'ToolTip': '这是一个按钮',
			'ContentReadonly': false,
			'SpecifyWidth': 10,
			'inputtype': 'button',
			'value': '按钮',
			'EnableValueValidate': true,
			'InnerEditStyle': 'input',
			'EditorActiveMode': 'MouseClick'
		};
		ctl.DCExecuteCommand('InsertInput', true, options);
		insertTemplateArr.push(options);
		this.setState({ counterObj, insertTemplateArr });
	}

	// 插入图片
	insertImage = () => {
		var ctl = document.getElementById(this.editorID);
		var obj = {
			id: '123',
			src: 'http://www.baidu.com/img/bd_logo1.png',
			width: '24',
			height: '24'
		};
		var arr = new Array();
		arr.push(obj);
		ctl.InsertImageByJsonText(arr);
		// ctl.DCExecuteCommand('DCInsertImage', false, 'http://www.baidu.com/img/bd_logo1.png');
	}

	// 插入批注
	NewComment = () => {
		let { userData } = this.state;
		var opts = {
			Text: '',
			Placeholder: '请点击编辑后添加批注。',
			UserName: userData && userData.userName ? userData.userName : '',
			UserID: userData && userData.userID ? userData.userID : '',
			BackgroundColor: 'skyblue',
		}
		document.getElementById(this.editorID).NewComment(opts);
	}

	// 插入xml字符串
	InsertXmlString = (nodeContent, rowData, fn) => {
		var ctl = document.getElementById(this.editorID);
		let option = {
			'Style': 'display:inline-block;'
		}
		var result = ctl.InsertXmlString(nodeContent, false, option);
		if (fn) {
			fn();
		}
	}

	// 插入病程
	insertTheCourseOfDisease = (selectionXml, recordID, tempalteData) => {
		console.log('tempalteData', tempalteData)
		var ctl = document.getElementById(this.editorID);
		var WCDoc = ctl.GetContentDocument();
		var WCBody = WCDoc.getElementById('divDocumentBody_0');
		let { forcedPageChange, newSource, dblclickID } = this.state;
		var dblclickDiv = ctl.GetContentDocument().getElementById(dblclickID);
		if (newSource !== 'external') {
			dblclickDiv && dblclickDiv.parentNode && dblclickDiv.parentNode.removeChild(dblclickDiv);
		}
		var options = new Array();
		var file = new Array();
		file.push(selectionXml);
		var attr1 = {
			'Attributes': {}, //自定义属性
			'DCTitle': '', //子文档标题
			'ReadOnly': 'false', //是否可编辑
			'Title': tempalteData?.descripts || tempalteData?.templateDesc || '', //文档标题
			'CSSStyle': 'border: 0; padding-bottom: 0px;',//样式
			// 'Style': 'border: 1px solid #808080;background-color: #FFF0F5;',//样式
			'ID': forcedPageChange ? 'paging' + recordID : 'record' + recordID, // 是否强制分页，强制分页则id以paging开头，用于打印预览时去除paddingBottom样式
			'TitleLevel': '0', // 用于病程定位
			'NewPage': forcedPageChange, // 插入的病程是否强制换页
		};
		// var result = ctl.InsertXmlString(selectionXml, true, options);
		options.push(attr1);
		var options = {
			Files: file,
			Options: options,
			Usebase64: 'false'
		};
		ctl.GetContentContainer && ctl.GetContentContainer().focus && ctl.GetContentContainer().focus();
		ctl.InsertSubDocuments(options, WCBody.lastChild);
		// 如果插入病程成功，则将dataSource合并
		for (var i = 0; i < this.state.courseOfDiseaseDataSource.length; i++) { // 合并病程数据并将updateFlag置为N
			this.state.courseOfDiseaseDataSource[i].updateFlag = 'N';
		}
		let newInsertTemplateArr = [...this.state.insertTemplateArr, ...this.state.courseOfDiseaseDataSource];
		this.setState({ insertTemplateArr: newInsertTemplateArr, forcedPageChange: false })
		// console.log(dblclickDiv, newTitleParentNode, this.state.dblclickDOM)
		setTimeout(() => {
			if (newSource !== 'external') {
				this.state.dblclickDOM && WCBody.appendChild(this.state.dblclickDOM);
			}
			this.handleCourseOfDiseaseCancel();
		}, 300)
	}

	// 新建病程
	addCourseOfDisease = () => {
		var ctl = document.getElementById(this.editorID);
		let { insertTemplateArr } = this.state;
		let isShowModal = false;
		let activeItem = {};
		let _this = this;
		for (var i = 0; i < insertTemplateArr.length; i++) {
			if (insertTemplateArr[i].fieldID === 'newtitle' && insertTemplateArr[i].type === 'T') {
				// console.log(insertTemplateArr[i])
				// 打开病程弹窗
				isShowModal = true;
				activeItem = insertTemplateArr[i];
				break;
			}
		}
		// 新建病程按钮
		let dblclickDOM = ctl.GetContentDocument && ctl.GetContentDocument().getElementById('newtitle') ? ctl.GetContentDocument().getElementById('newtitle') : this.state.dblclickDOM;
		if (isShowModal) {
			_this.handleShowCourseOfDisease(activeItem, dblclickDOM, '')
		} else {
			message.error("当前模板暂不支持插入病程。")
		}
	}

	// 删除病程
	removeCourseOfDisease = () => {
		var ctl = document.getElementById(this.editorID);
		var myHtml = ctl.GetContentDocument();
		var myDiv = myHtml.querySelectorAll("div[dctype='XTextSubDocumentElement']");
		if (!(myDiv && myDiv.length > 0)) {
			message.error("当前模板暂无可删除的病程。")
			return;
		}; // 不存在病程时候
		var $box = $(ctl.DocumentSelection().currentContainer.parentElement).parents("div[dctype='XTextSubDocumentElement']");//获取光标所在的子病程div
		let isExistence = false;
		for (var i = 0; i < myDiv.length; i++) {
			if (myDiv[i] == $box[0]) {
				isExistence = true;
				break;
			}
		}
		// console.log(myDiv, $box)
		if (isExistence) {
			$box.remove();
			// this.props.handleDelete("removeCourse", $box[0] && $box[0].id ? $box[0].id.substring(6) : ''); // 删除目录树子病程节点
		} else {
			message.error("请将光标放到病程中的某个输入框当中再操作删除功能。")
		}
	}

	// 上移病程
	courseOfDiseaseMoveUp = () => {
		var ctl = document.getElementById(this.editorID);
		var myHtml = ctl.GetContentDocument();
		var myDiv = myHtml.querySelectorAll("div[dctype='XTextSubDocumentElement']");
		var currentDom = ctl.CurrentInputField(); // 获取当前光标所在的输入域
		if (!(myDiv && myDiv.length > 0)) {
			message.error("当前模板暂无可移动的病程。")
			return;
		}; // 不存在病程时候
		if (myDiv && myDiv.length === 1) {
			message.error("当前模板只有一个病程，暂不支持上移。")
			return;
		}
		var $box = $(ctl.DocumentSelection().currentContainer.parentElement).parents("div[dctype='XTextSubDocumentElement']");//当前子病程
		// console.log($box)
		let isExistence = false;
		let index = 0;
		for (var i = 0; i < myDiv.length; i++) {
			if (myDiv[i] == $box[0]) {
				isExistence = true;
				index = i;
				break;
			}
		}
		if (isExistence) {
			$(myDiv[index - 1]).before($box);
			setTimeout(() => {
				// let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldID)
				currentDom && currentDom.focus()
			}, 300);
		} else {
			message.error("请将光标放到病程中的某个输入框当中再操作上移功能。")
		}
	}

	// 下移病程
	courseOfDiseaseMoveDown = () => {
		var ctl = document.getElementById(this.editorID);
		var myHtml = ctl.GetContentDocument();
		var currentDom = ctl.CurrentInputField(); // 获取当前光标所在的输入域
		var myDiv = myHtml.querySelectorAll("div[dctype='XTextSubDocumentElement']");//获取所有病程
		if (!(myDiv && myDiv.length > 0)) {
			message.error("当前模板暂无可移动的病程。")
			return;
		}; // 不存在病程时候
		if (myDiv && myDiv.length === 1) {
			message.error("当前模板只有一个病程，暂不支持下移。")
			return;
		}
		var $box = $(ctl.DocumentSelection().currentContainer.parentElement).parents("div[dctype='XTextSubDocumentElement']");
		let isExistence = false;
		let index = 0;
		for (var i = 0; i < myDiv.length - 1; i++) {
			if (myDiv[i] == $box[0]) {
				isExistence = true;
				index = i;
				break;
			}
		}
		if (isExistence) {
			$(myDiv[index + 1]).after($box);
			setTimeout(() => {
				// let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldID)
				currentDom && currentDom.focus()
			}, 300);
		} else {
			message.error("请将光标放到病程中的某个输入框当中再操作下移功能。")
		}
	}

	// 清除病程样式
	clearCourseDiseaseStyle = () => {
		var ctl = document.getElementById(this.editorID);
		var doc = ctl.GetContentDocument();
		$(doc).find("[dctype=\"XTextSubDocumentElement\"]").removeAttr("style");
	}

	// 添加病程样式
	addCourseDiseaseStyle = () => {
		var ctl = document.getElementById(this.editorID);
		var doc = ctl.GetContentDocument();
		$(doc).find("[dctype=\"XTextSubDocumentElement\"]").attr({ style: "border: 1px solid #808080;background-color: #FFF0F5;" });
	}

	// 插入表格
	insertTable = (tableRow, tableColumn) => {
		var ctl = document.getElementById(this.editorID);
		let { counterObj } = this.state;
		counterObj.tabID = counterObj.tabID ? counterObj.tabID + 1 : 1;
		let parameter = {
			'RowCount': tableRow,
			'ColumnCount': tableColumn,
			'TableID': `table${counterObj.tabID}`
		};
		ctl.DCExecuteCommand('InsertTable', true, parameter);
		this.setState({ counterObj })
	}

	// 插入分页
	InsertPageBreak = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('InsertPageBreak', false, null);
	}

	// 删除表格或行、列
	detailTable = (status) => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand(status, false, null);
	}

	// 插入表格行、列
	insertTableRow = (status) => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand(status, false, null);
	}

	// 动态下拉列表
	dynamicDropDownList = (record, flag) => {
		let { insertTemplateArr, counterObj } = this.state;
		let obj = JSON.parse(JSON.stringify(record));

		counterObj[obj.code] = counterObj[obj.code] ? counterObj[obj.code] + 1 : 1;
		obj.fieldID = 'basics' + obj.code + counterObj[obj.code];

		flag === "no" ? '' : insertTemplateArr.push(obj);

		this.setState({ insertTemplateArr, counterObj }, () => {
			var ctl = document.getElementById(this.editorID);
			var options = {
				"ID": obj.fieldID ? obj.fieldID : '',
				"BackgroundText": obj.descripts ? obj.descripts : '下拉列表',
				"ToolTip": obj.descripts ? obj.descripts : '下拉列表',
				"InnerEditStyle": "DropdownList",
				"Innerlistsourcename": flag === "no" ? obj.code : obj.fieldID, // 对映上name
				"EditorActiveMode": "MouseClick",
				"Name": "select"
			};
			var field = ctl.DCExecuteCommand("InsertInputField", true, options);
		})
	}

	// 插入单选框/复选框
	insertCheckboxRadio = (data, flag, record) => {
		let { counterObj } = this.state;
		let obj = JSON.parse(JSON.stringify(record))
		counterObj[obj.code] = counterObj[obj.code] ? counterObj[obj.code] + 1 : 1;
		obj.fieldID = obj.code + counterObj[obj.code];
		this.setState({ counterObj }, () => {
			var ctl = document.getElementById(this.editorID);
			var options = {
				"Name": obj.code, //单选框的Name属性相同
				"Type": flag, //radio、checkbox
				"ListItems": data
			};
			ctl.DCExecuteCommand("insertcheckboxorradio", true, options);
		})
	}

	// 关闭自定义数据弹窗
	handleCancel = () => {
		this.setState({ visible: false });
	}

	showModal = (id) => {
		let { insertTemplateArr } = this.state;
		let activeKey = [];
		for (var i = 0; i < insertTemplateArr.length; i++) { // 如果以及绑定自定义数据则选中这条数据
			if (insertTemplateArr[i].fieldID === id && insertTemplateArr[i].customID) {
				activeKey.push(insertTemplateArr[i].customID)
				break;
			}
		}
		this.setState({
			modalSelectedKeys: activeKey,
			visible: true,
			dbModalId: id
		}, () => {
			if (!(this.state.customDataSet && this.state.customDataSet.length > 0)) {
				this.getCustomDataSet(); // 获取自定义数据集
			}
		});
	};

	handleOk = () => {
		let { insertTemplateArr, dbModalId, modalTreeSelectData } = this.state;
		for (var i = 0; i < insertTemplateArr.length; i++) {
			if (insertTemplateArr[i].fieldID === dbModalId) {
				insertTemplateArr[i].customID = modalTreeSelectData.ID;
				break;
			}
		}
		this.setState({ insertTemplateArr }, () => {
			this.handleCancel();
		});
	}

	renderCustomDataSetTreeNodes = data => data.map(item => {
		const index = item.descripts.indexOf(this.state.dataSetValue);
		const beforeStr = item.descripts.substr(0, index);
		const afterStr = item.descripts.substr(index + this.state.dataSetValue && this.state.dataSetValue.length);
		const title = index > -1 ? (
			<span>
				{beforeStr}
				<span style={{ color: '#FF7F00' }}>{this.state.dataSetValue}</span>
				{afterStr}
			</span>
		) : <span>{item.descripts}</span>;
		if (item.children && item.children.length > 0) {
			return (
				<TreeNode title={title} key={item.key} dataRef={item}>
					{this.renderCustomDataSetTreeNodes(item.children)}
				</TreeNode>
			);
		}
		return <TreeNode title={title} key={item.key} {...item} dataRef={item} />;
	})

	// 获取自定义数据集
	getCustomDataSet = () => {
		let data = {
			params: [{
				ID: '', // 表ID
				code: '', // 数据集代码
				descripts: '', // 数据集描述
				serviceCode: '', // 服务代码
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010017",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for (var i = 0; i < res.result.length; i++) {
						res.result[i].key = 'main' + res.result[i].ID;
					}
					this.setState({ customDataSet: res.result })
				}
			}
		})
	}

	// 异步加载数据集的子数据数据
	onLoadData = treeNode =>
		new Promise(resolve => {
			if (!treeNode.props.serviceCode || treeNode.props.children) {
				resolve();
				return;
			}
			let ID = treeNode.props.dataRef.ID;
			let data = {
				params: [{
					code: '', // 数据集代码
					descripts: '', // 数据集描述
					CBEMRDSRParRef: ID,
				}],
				pagination: [{
					pageSize: 1000,
					currentPage: 1
				}]
			}
			$http.post('urlS', this, {
				code: "06010025",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result) {
						for (var i = 0; i < res.result.length; i++) {
							res.result[i].key = res.result[i].ID;
							res.result[i].isLeaf = true;
							res.result[i].serviceCode = treeNode.props.serviceCode;
							res.result[i].type = 'C',
								res.result[i].customID = res.result[i].ID;
						}
						treeNode.props.dataRef.children = res.result;
						// console.log(this.state.customDataSet)
						this.setState({
							customDataSet: [...this.state.customDataSet],
						});
						resolve();
					} else {
						resolve();
					}
				}
			})
		}
		)

	modalOnSelect = (keys, event) => {
		// console.log(keys, event)
		this.setState({ modalSelectedKeys: keys }, () => {
			if (this.state.modalSelectedKeys && this.state.modalSelectedKeys.length > 0) {
				this.setState({ modalTreeSelectData: event.node.props.dataRef })
			}
		})
	}

	// 加载模板将模板所存dataSource赋值给insertTemplateArr
	setInsertTemplateArr = (dataSource, releaseFlag) => {
		// console.log(dataSource)
		var ctl = document.getElementById(this.editorID);
		var field = ctl.GetContentDocument().getElementById("dcGlobalRootElement");
		this.setState({ insertTemplateArr: dataSource, isOperable: releaseFlag, operableWidth: field && field.width ? field.width : 0 })
	}

	// 插入上标
	handleSuperscript = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Superscript', true, null);
	}

	// 插入上标
	handleSubscript = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('Subscript', true, null);
	}

	// 删除表格边框
	SetTableBorder = (obj) => {
		var opts = {
			BorderLeft: obj.BorderLeft ? obj.BorderLeft : "true",
			BorderTop: obj.BorderTop ? obj.BorderTop : "true",
			BorderBottom: obj.BorderBottom ? obj.BorderBottom : "true",
			BorderRight: obj.BorderRight ? obj.BorderRight : "true",
			BorderWidth: 0
		}
		var ctl = document.getElementById(this.editorID);
		var table = ctl.CurrentTable();
		ctl.SetTableBorder(table, opts);
	}

	// 根据id获取病程的xml串
	GetCourseRecordXML = (type) => {
		let ctl = document.getElementById(this.editorID);
		//获取所有病程
		let allCourseOfDisease = ctl && ctl.GetCourseRecords ? ctl.GetCourseRecords() : [];
		let recordDataSource = [];
		for (let i = 0; i < allCourseOfDisease.length; i++) {
			let id = allCourseOfDisease[i]?.ElementID || '';
			if (id) {
				let recordID = id.substring(6);
				if (type === 'inputArr') {
					let fieldList = [];
					let doc = ctl && ctl.GetContentDocument().getElementById(id);
					let inputs = $(doc).find("[dctype='XTextInputFieldElement']"); // JQUERY
					for (let i = 0; i < inputs.length; i++) {
						let index = i;
						let fieldID = inputs.eq(index).attr('id');
						let value = ctl.GetElementTextByID(fieldID, id); // 获取病程中的内容
						if (value) {
							fieldList.push({
								fieldID,
								value
							})
						}
					}
					recordDataSource.push({
						recordID,
						dataSource: fieldList,
					})
				} else {
					recordDataSource.push(recordID)
				}
			}
		}
		return recordDataSource;
	}

	LoadDocumentFromString = () => {
		var ctl = document.getElementById(this.editorID);
		ctl.LoadDocumentFromString(strContent, fileFormat)
	}

	// 加载xml
	handleLoadXML = (xml, isAjaxLoad, templateParams) => {
		if (isAjaxLoad === 'Y') {
			if (xml) {
				this.setState({ loadXMLStr: xml }, () => {
					this.setElementTextByID(...templateParams);
				})
			} else {
				this.setElementTextByID(...templateParams);
			}
		} else {
			this.setState({ loadXMLStr: '' }, () => {
				let ctl = document.getElementById(this.editorID);
				xml && ctl.LoadDocumentFromString(xml, 'xml');
			})
		}
	}

	// 插入章节名称
	handleSetChapter = () => {
		var ctl = document.getElementById(this.editorID);
		let { counterObj } = this.state;
		counterObj.chapter = counterObj.chapter ? counterObj.chapter + 1 : 1;
		let options = {
			'ContentReadonly': false,
			'ToolTip': '',
			'BackgroundText': '',
			'BackgroundColor': 'white',
			'Text': '',
			'InnerValue': '',
			'Name': '',
			'StartBorderText': ' ',
			'EndBorderText': ' ',
			'ID': 'chapter' + counterObj.chapter,
		};
		var field = ctl.DCExecuteCommand('InsertInputField', true, options);
		if (field != null) {
			ctl.FocusAdjacent('afterEnd', field); //这里的第一个参数可以是beforeBegin,afterBegin,beforeEnd,afterEnd
		}
		this.setState({ counterObj })
	}

	// 将章节名称设为不可编辑不可删除
	clearChapterStyle = (bool) => {
		var inputAll = document.getElementById(this.editorID).GetAllInputFields(false, false);
		for (var i = 0; i < inputAll.length; i++) {
			if (inputAll[i].id.substring(0, 7) === 'chapter') {
				inputAll[i].setAttribute('contenteditable', bool); //只读
				inputAll[i].setAttribute('dc_deleteable', bool); //不可删除
				// inputAll[i].setAttribute('dc_contentreadonly', true); //只读
			}
		}
	}

	// 章节过滤
	handleFilterChapters = (flag) => {
		if (flag !== '女性') {
			var ctl = document.getElementById(this.editorID);
			//获取所有病程
			var arr = ctl.GetCourseRecords();
			if (!(arr && arr.length > 0)) {
				return;
			}
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].ElementID.substring(6, 12) === 'FILTER') {
					// console.log(arr[i].Element)
					arr[i].Element.setAttribute('style', 'display: none')
				}
			}
		}
	}

	validateResult_Click() {
		var sel = document.getElementById('validateResult');
		if (sel == null || sel.selectedIndex < 0) {
			return;
		}
		var opt = sel.options[sel.selectedIndex];
		var result = opt.result;
		result.Select();
	}

	readNum = (e) => {
		this.setState({
			readNum: e
		})
		switch (e) {
			case 1:
				this.ClosePrintPreview()
				break;
			case 2:
				this.OpenPreview()
				break;
			case 3:
				this.readingHistory()
				break;

			default:
				break;
		}
	}

	readingHistory = (e) => {
		this.setState({
			readingHistory: true
		})
	}

	// 关闭病程弹窗
	handleCourseOfDiseaseCancel = () => {
		this.setState({ courseOfDiseaseVisible: false, courseOfDiseaseLoading: false })
	}

	handleShowCourseOfDisease = (item, dom, newSource) => {
		// console.log(item, dom, newSource)
		this.setState({ courseOfDiseaseVisible: true, dblclickID: dom?.id || '', dblclickDOM: dom || '', newSource }, () => {
			this.getTemplateSelectData(item);
		})
	}

	handleCourseOfDiseaseChange = e => {
		this.setState({ courseOfDiseaseValue: e, courseID: '', courseOfDiseaseLoading: true }, () => {
			this.handleLoadingDocuments(); // 获取病历加载地址
			this.caseInformationChild.clearKnowledgeBaseTreeData(); // 清除知识库内容
		})
	}

	// 获取模板下拉数据
	getTemplateSelectData = (item) => {
		let { versionID } = this.state;
		let data = {
			params: [{
				versionID,
				EMRProgTitleAvailable: 'Y', // 获取有效模板
				fieldID: item.fieldID || ''
			}]
		}
		$http.post('urlDeault', this, {
			code: '06060108',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({ templateSelectData: res.result.linkTemplateData })
				} else {
					this.setState({ templateSelectData: [] })
				}
			}
		})
	}

	// 根据ID加载电子病历模板
	handleLoadingDocuments = () => {
		let { courseOfDiseaseValue, userData } = this.state;
		let recordData = sessionStorage.getItem('patientData') ? JSON.parse(sessionStorage.getItem('patientData')) : {};
		let data = {
			params: [{
				// EMRTemplateID: courseOfDiseaseValue, // 模板版本ID
				ID: courseOfDiseaseValue,
				admID: recordData && recordData.admID ? recordData.admID : '',
				hospID: userData && userData.hospID ? userData.hospID : '',
				// xmlFlag: 'Y'
			}]
		}
		$http.post('urlS', this, {
			code: '06020045', // 06020023
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log(res)
					let { templatePath, dataSource } = res.result;
					this.setState({ courseOfDiseaseTemplatePath: templatePath, courseOfDiseaseDataSource: dataSource }, () => {
						this.loadCourseOfDiseaseTemplate();
					})
				} else {
					this.clearCourseOfDiseaseLoading();
				}
			},
			error: function () {
				this.clearCourseOfDiseaseLoading()
			}
		})
	}

	handlePreviewTemplateRef = ref => {
		this.courseOfDiseaseChild = ref;
	}

	loadCourseOfDiseaseTemplate = () => {
		let { courseOfDiseaseTemplatePath, courseOfDiseaseDataSource } = this.state;
		if (this.courseOfDiseaseChild && this.courseOfDiseaseChild.setElementTextByID) {
			if (courseOfDiseaseTemplatePath) {
				setTimeout(() => {
					this.courseOfDiseaseChild.setElementTextByID(courseOfDiseaseTemplatePath, courseOfDiseaseDataSource, '', '', this.clearCourseOfDiseaseLoading)
				}, 300)
			} else {
				this.courseOfDiseaseChild.NewFile();
				this.clearCourseOfDiseaseLoading();
			}
		} else {
			courseOfDiseaseTemplateCount++
			if (courseOfDiseaseTemplateCount < 5) {
				setTimeout(() => {
					this.loadCourseOfDiseaseTemplate()
				}, 300)
			} else {
				this.clearCourseOfDiseaseLoading()
			}
		}
	}

	clearCourseOfDiseaseLoading = () => {
		this.setState({ courseOfDiseaseLoading: false });
	}

	// 确认插入病程
	handleCourseOfDiseaseOk = () => {
		// var ctl = document.getElementById(this.editorID);
		let { courseOfDiseaseValue, templateSelectData } = this.state;
		if (!courseOfDiseaseValue) {
			message.error('请选择需要插入的模板。');
			return;
		}
		if (this.state.courseOfDiseaseLoading) return;
		this.setState({ courseOfDiseaseLoading: true });
		let templateData = this.courseOfDiseaseChild.getTemplateXml('release');
		let templatePath = templateData.xmlStr;
		let currentTemplateData = {};
		for (var i = 0; i < templateSelectData.length; i++) {
			if (templateSelectData[i].newestVersionID === courseOfDiseaseValue) {
				currentTemplateData = templateSelectData[i];
				break;
			}
		}
		this.props.handleSaveTheInsertedCourse(templatePath, currentTemplateData?.templateID || '', currentTemplateData);
		// this.insertTheCourseOfDisease(templatePath, {}, this.handleCourseOfDiseaseCancel)
	}

	// 重新加载该组件
	handleOnReload = () => {
		if (this.props.handleOnReload) {
			this.props.handleOnReload()
		}
		// window.location.reload();
	}

	// 确认
	handleDropDownSearchOk = () => {
		try {
			let { selectRowData, modalRowData } = this.state;
			let IDCollection = this.state.IDCollection && this.state.IDCollection.length > 0 ? JSON.parse(JSON.stringify(this.state.IDCollection)) : [];
			// IDCollection为选择的filedID对应的数据ID集合
			var ctl = document.getElementById(this.editorID);
			let oldFieldID = '';
			// console.log('selectRowData', selectRowData)
			if (selectRowData && selectRowData.linkItem && selectRowData.linkItem.length && selectRowData.linkItem.length > 0) { // 给相关绑定的输入域赋值
				// console.log('触发了if', modalRowData)
				for (var i = 0; i < selectRowData.linkItem.length; i++) {
					ctl.SetElementTextByID(selectRowData.linkItem[i].fieldID, modalRowData[selectRowData.linkItem[i].linkResCode], selectRowData?.recordDOMID || '');
					oldFieldID = selectRowData.linkItem[i].fieldID;
					IDCollection.push({ fieldID: selectRowData.linkItem[i].fieldID, valueID: modalRowData && modalRowData.id ? modalRowData.id : '', recordDOMID: selectRowData?.recordDOMID || '' })
				}
			} else {
				// console.log('触发了else', modalRowData)
				let currentDom = ctl.CurrentInputField();
				if (currentDom && currentDom.firstChild && currentDom.firstChild.nextSibling && currentDom.firstChild.nextSibling.outerHTML) {
					currentDom.firstChild.nextSibling.outerHTML = '<span>' + (modalRowData?.descripts || '') + '</span>';
					currentDom?.focus();
					this.handleRecordInputCopysource(currentDom?.id || '', currentDom.dc_innervalue || currentDom.dc_innertext);
				} else {
					var result = ctl.SetElementTextByID(selectRowData.fieldID, modalRowData && modalRowData.descripts ? modalRowData.descripts : '', selectRowData?.recordDOMID || '');
				}
				oldFieldID = selectRowData.fieldID;
				IDCollection.push({ fieldID: selectRowData.fieldID, valueID: modalRowData && modalRowData.id ? modalRowData.id : '', recordDOMID: selectRowData?.recordDOMID || '' })
			}
			if (selectRowData && selectRowData.fieldID) {
				this.setState({ IDCollection })
				this.handleDropDownSearchCancel();
				let nextFieldArr = this.getNextFieldID(oldFieldID, 'arr', 'all');
				if (nextFieldArr && nextFieldArr.length === 1) {
					setTimeout(() => {
						let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldArr[0]);
						// nextFieldDOM && nextFieldDOM.focus && $(nextFieldDOM).focus();
						ctl.FocusAdjacent('afterBegin', nextFieldDOM)
					}, 300);
				}
			}
		} catch (error) {
			console.log(error);
			this.handleDropDownSearchCancel();
		}
	}

	// 关闭搜索选择弹窗
	handleDropDownSearchCancel = () => {
		this.setState({ dropDownSearch: false }, () => {
			this.setState({ modalRowId: '', modalRowData: {}, selectCode: undefined, selectDesc: undefined, })
		})
	}

	// 获取代码
	getSelectCodeValue = (e) => {
		this.setState({ selectCode: e.target.value })
	}

	// 获取描述
	getSelectDescValue = (e) => {
		this.setState({ selectDesc: e.target.value })
	}

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ modalPage: page, modalPageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}

	// 查询
	handleQuery = () => {
		let { selectRowData } = this.state;
		if (selectRowData && selectRowData.serviceCode) {
			this.setState({ modalPage: 1 }, () => {
				this.getTableData();
			})
		}
	}

	getTableData = () => {
		let { selectDesc, selectRowData, modalPage, modalPageSize } = this.state;
		let recordData = sessionStorage.getItem('patientData') ? JSON.parse(sessionStorage.getItem('patientData')) : {};
		this.setState({ modalLoading: true })
		let data = {
			params: [{
				searchWords: selectDesc,
				admID: recordData && recordData.admID ? recordData.admID : '',
			}],
			pagination: [{
				pageSize: modalPageSize,
				currentPage: modalPage
			}]
		}
		setTimeout(() => {
			var gunDong = document.getElementById('gundong');
			if (gunDong) {
				gunDong.scrollTop = 0;
			}
		}, 100)
		$http.post('urlDeault', this, {
			code: selectRowData.serviceCode,
			data: data,
			success: (res) => {
				this.modalRef && this.modalRef.handleLoading && this.modalRef.handleLoading();
				this.setState({ modalLoading: false })
				if (+res.errorCode === 0) {
					let modalTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
					for (var i = 0; i < modalTableData.length; i++) {
						modalTableData[i].key = i + 1
					}
					this.setState({ modalTableData, modalTotal: res.result && res.result.totalCount ? res.result.totalCount : 0 });
				} else {
					this.setState({ modalTableData: [], modalTotal: 0 });
				}
			},
			error: () => {
				this.modalRef && this.modalRef.handleLoading && this.modalRef.handleLoading();
				this.setState({ modalTableData: [], modalTotal: 0 });
			}
		})
	}

	onModalRef = ref => {
		this.modalRef = ref;
	}

	// 操作行
	onClickRowPublic = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.modalRowId === '') {
					// 保存行数据以及ID
					this.setState({ modalRowId: record.key, modalRowData: record })
				} else {
					if (this.state.modalRowId !== record.key) {
						this.setState({ modalRowId: record.key, modalRowData: record })
					}
				}
			},
			onDoubleClick: () => {
				this.setState({ modalRowId: record.key, modalRowData: record }, () => {
					this.handleDropDownSearchOk()
				})
			}
		}
	}

	// 选中行操作
	setRowClassNamePublic = (record) => {
		return record.key === this.state.modalRowId ? 'clickRowStyle' : '';
	}

	handleCaseInformationRef = ref => {
		this.caseInformationChild = ref;
	}

	// 供病历公共组件调用获取知识库数据
	getChildKnowledgeBaseTreeData = (filedId) => {
		let { courseOfDiseaseValue } = this.state;
		// console.log('page', filedId, this.state.modalRowData)
		if (this.state.courseID !== filedId) {// 点击同一个病程则不再调用查询知识库方法
			let data = {
				releaseVersion: courseOfDiseaseValue
			}
			this.setState({ courseID: filedId }, () => {
				this.caseInformationChild.getKnowledgeBaseTreeData(this.state.courseID, data);
			})
		}
	}

	// 新知识库赋值
	courseOfDiseaseKnowledgeBaseAssignment = (filedID, value) => {
		this.courseOfDiseaseChild && this.courseOfDiseaseChild.knowledgeBaseAssignment && this.courseOfDiseaseChild.knowledgeBaseAssignment(filedID, value);
	}

	// 插入知识库xml
	setKnowledgeBaseXMl = (nodeContent, rowData, fn) => {
		// console.log(nodeContent, rowData, fn)
		this.courseOfDiseaseChild && this.courseOfDiseaseChild.InsertXmlString && this.courseOfDiseaseChild.InsertXmlString(nodeContent, rowData, fn)
	}

	// 获取当前病历模板所有的输入域ID以及对应的value
	getMedicalRecordFileIDAndValue = (type) => {
		let IDCollection = this.state.IDCollection && this.state.IDCollection.length > 0 ? this.state.IDCollection : [];
		var ctl = document.getElementById(this.editorID);
		var doc = ctl && ctl.GetContentDocument();
		var inputs = $(doc).find("[dctype='XTextInputFieldElement']"); // JQUERY
		var fieldList = [];
		for (let i = 0; i < inputs.length; i++) {
			let index = i;
			let fieldID = inputs.eq(index).attr('id');
			let value = ctl.GetElementTextByID(fieldID);
			// let value = inputs.eq(index).attr('dc_innervalue') || inputs.eq(index).attr('dc_innertext'); // 解决ID重复取值的问题/存在的问题就是框嵌套框的时候外层框取不到里层框修改的最新内容
			let keyObject = {
				fieldID,
				value,
				valueID: undefined
			}
			// 根据fieldID取出弹窗选择的数据对应的valueID
			for (var j = 0; j < IDCollection.length; j++) {
				if (fieldID === IDCollection[j].fieldID) {
					keyObject.valueID = IDCollection[j].valueID
				}
			}
			if (value || (type === 'all')) {
				fieldList.push(keyObject)
			}
		}
		return fieldList;
	}

	// 键盘操作名称模态框数据
	handlePublicModalTableOnKeydown = (e) => {
		var e = window.event || e;
		let scroll_height = 32;
		let id = '';
		let oneArr = this.state.modalTableData && this.state.modalTableData.length > 0 ? this.state.modalTableData : [];
		switch (e.keyCode) {
			case 13:
				if (this.state.modalRowId) {
					let obj = {}
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							obj = i > 0 ? oneArr[i] : oneArr[0];
							break;
						}
					}
					this.setState({ modalRowId: obj.key, modalRowData: obj }, () => {
						this.handleDropDownSearchOk()
					})
				} else {
					message.info('请选择需要操作的数据。')
				}
				break;
			case 38: //上
				if (this.state.modalRowId) {
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
							break;
						}
					}
					this.setState({ modalRowId: id })
					setTimeout(() => {
						var gunDong = document.getElementById('gundong');
						if (gunDong) {
							gunDong.scrollTop = gunDong.scrollTop - scroll_height;
						}
					}, 100)
				} else {
					this.setState({ modalRowId: oneArr[0].key })
				}
				break;
			case 40: //下
				if (this.state.modalRowId) {
					for (let i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
							break;
						}
					}
					this.setState({ modalRowId: id })
					setTimeout(() => {
						var gunDong = document.getElementById('gundong');
						if (gunDong) {
							gunDong.scrollTop = gunDong.scrollTop + scroll_height;
						}
					}, 100)
				} else {
					this.setState({ modalRowId: oneArr[0].key })
				}
				break;
		}
	};

	// 插入的病程是否强制分页
	handleForcedPageChange = e => {
		this.setState({ forcedPageChange: e.target.checked })
	}

	// 选择指定打印页
	handlePrintSpecifiedPageChange = value => {
		let chkJumpPrintID = this.editorID + 'chkJumpPrint';
		this.setState({ printSpecifiedPage: value }, () => {
			// 取消续打
			this.handleJumpPrint(false, 'N')
			if (document.getElementById(chkJumpPrintID)) {
				document.getElementById(chkJumpPrintID).checked = false;
			}
		})
	}

	// 指定分页的下拉数据
	printSpecifiedPageOption = () => {
		let { pageNum } = this.state;
		const children = [];
		for (let i = 0; i < pageNum; i++) {
			children.push(<Option key={i + 1} value={String(i + 1)}>{i + 1}</Option>);
		}
		return children;
	}

	// 关闭诊断弹窗
	handleDiagnosisSearchCancel = () => {
		this.setState({ diagnosisSearch: false })
	}

	// 插入诊断
	handleDiagnosisSearchOk = (clickSource) => {
		// 插入诊断前先判断是否有需要保存的数据
		let isSave = this.showDiagnosisChild && this.showDiagnosisChild.handleDetermineWhetherToSave ? this.showDiagnosisChild.handleDetermineWhetherToSave() : true;
		if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
			this.showDiagnosisChild.saveDiagnosisMsg && this.showDiagnosisChild.saveDiagnosisMsg(clickSource);
		} else {
			let diagDescArr = this.showDiagnosisChild && this.showDiagnosisChild.getSelectedRows ? this.showDiagnosisChild.getSelectedRows() : [];
			if (diagDescArr && diagDescArr.length > 0) {
				this.handleInsertDiagnosis(diagDescArr, 'checkout');
			} else {
				let { diagnosisRowData } = this.state;
				let recordData = sessionStorage.getItem('patientData') ? JSON.parse(sessionStorage.getItem('patientData')) : {};
				// console.log('insertMethod', insertMethod)
				let data = {
					params: [{
						admID: recordData && recordData.admID ? recordData.admID : ''
					}]
				}
				$http.post('urlS', this, {
					code: diagnosisRowData && diagnosisRowData.serviceCode ? diagnosisRowData.serviceCode : '',
					data: data,
					success: function (res) {
						if (+res.errorCode === 0) {
							let diagnosisSourse = res.result;
							this.handleInsertDiagnosis(diagnosisSourse);
						}
					}
				})
			}
		}
	}

	// 插入诊断
	handleInsertDiagnosis = (diagnosisSourse, sourse) => {
		var ctl = document.getElementById(this.editorID);
		let { diagnosisRowData } = this.state;
		let insertMethod = this.showDiagnosisChild && this.showDiagnosisChild.getInsertMethod ? this.showDiagnosisChild.getInsertMethod() : 'transverse'; // 横排： transverse  竖排： vertical
		// let oldFieldID = '';
		// console.log('diagnosisRowData', diagnosisRowData, diagnosisSourse)
		if (diagnosisRowData && diagnosisRowData.linkItem && diagnosisRowData.linkItem.length && diagnosisRowData.linkItem.length > 0) { // 给相关绑定的输入域赋值
			for (var i = 0; i < diagnosisRowData.linkItem.length; i++) {
				// 需要插入的数据源，如果勾选则插入勾选的数据，没有勾选则根据后台返回插入同类型数据
				let domValueData = sourse === 'checkout' ? diagnosisSourse : diagnosisSourse[diagnosisRowData.linkItem[i].linkResCode], domValue = '';
				if (domValueData && domValueData.length > 0) { // 获取到诊断数据前端根据排列方式拼接插入
					for (var j = 0; j < domValueData.length; j++) {
						domValue += (j + 1) + '、' + domValueData[j] + (insertMethod === 'vertical' ? ((j === domValueData.length - 1) ? '' : '</br>') : '  ');
					}
				} else {
					message.error('请勾选或者录入同类诊断再进行插入。');
					return;
				}
				ctl.SetElementTextByID(diagnosisRowData.linkItem[i].fieldID, domValue, diagnosisRowData?.recordDOMID || '');
			}
		} else { // 如果linkItem为空则插入到当前的输入域
			if (diagnosisSourse && diagnosisSourse.length > 0) {
				let domValue = '';
				for (var k = 0; k < diagnosisSourse.length; k++) {
					domValue += (k + 1) + '、' + diagnosisSourse[k] + (insertMethod === 'vertical' ? ((k === diagnosisSourse.length - 1) ? '' : '</br>') : '  ');
				}
				ctl.SetElementTextByID(diagnosisRowData.fieldID, domValue, diagnosisRowData?.recordDOMID || '');
			} else {
				message.error('请勾选或者录入同类诊断再进行插入。');
				return;
			}
		}
		this.handleDiagnosisSearchCancel(); // 关闭插入弹窗
		// this.showDiagnosisChild && this.showDiagnosisChild.clearCheckout && this.showDiagnosisChild.clearCheckout(); // 清除诊断列表选中数据
	}

	showDiagnosisRef = ref => {
		this.showDiagnosisChild = ref;
	}

	// 获取引用规则
	getRuleOfReference = async (ruleCode) => {
		let ruleOfReferences = '';
		try {
			let data = {
				params: [{
					power: 'DocEMRResource',
					eMRResourceRuleCode: ruleCode
				}]
			}
			let res = await React.$asyncPost(this, '06010079', data);
			ruleOfReferences = res?.result || '';
			// ruleOfReferences = ruleOfReferences.replace('medDesc', 'ordMedItemDesc'); // 医嘱名称
			// ruleOfReferences = ruleOfReferences.replace('ordUsageDesc', 'ordUsageDesc'); // 用法 
			ruleOfReferences = ruleOfReferences.replace('ordDoseUnit', 'ordDoseQtyUnit'); // 剂量 
			ruleOfReferences = ruleOfReferences.replace('ordFreqDesc', 'ordFrequenceDesc'); // 频次
			// ruleOfReferences = ruleOfReferences.replace('ordbodyPartDesc', 'ordbodyPartDesc'); // 部位
		} catch (error) {
			ruleOfReferences = '';
			console.log(error)
		}
		return ruleOfReferences;
	}

	// 医嘱引用规则
	handleRuleReference = (arr, values) => {
		let insertMethod = this.depAdviceRef && this.depAdviceRef.getInsertMethod ? this.depAdviceRef.getInsertMethod() : 'transverse'; // 横排： transverse  竖排： vertical
		let valueArr = values.split('+');
		let str = ''
		for (let i = 0; i < arr.length; i++) {
			str += i + 1 + '、';
			for (let j = 0; j < valueArr.length; j++) {
				if (arr[i][valueArr[j]]) {
					str += arr[i][valueArr[j]] + '  ';
				}
			}
			str += (insertMethod === 'vertical' ? ((i === arr.length - 1) ? '' : '</br>') : '  ');
		}
		return str;
	}

	/**
	 * @ByShizi: 新增医嘱录入弹窗操作
	 * Create 2022-08-10
	 * */
	handleMedicalOrderOk = async (clickSource) => {
		var ctl = document.getElementById(this.editorID);
		let { medicalOrderData, ruleOfReferences } = this.state;
		if (!ruleOfReferences) {
			ruleOfReferences = await this.getRuleOfReference('QuoteResourcesOrder');
			this.setState({ ruleOfReferences });
		}
		// 插入诊断前先判断是否有需要保存的数据
		let isSave = this.depAdviceRef && this.depAdviceRef.handleDetermineWhetherToSave ? this.depAdviceRef.handleDetermineWhetherToSave() : true;
		if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
			this.depAdviceRef.insuTypeCodeFlagFun && this.depAdviceRef.insuTypeCodeFlagFun(clickSource);
		} else {
			let medOrderArr = this.depAdviceRef && this.depAdviceRef.getSelectedRows ? this.depAdviceRef.getSelectedRows() : [];
			medOrderArr = medOrderArr && medOrderArr.filter(item => !!(item.ordMedItemDesc));
			if (medOrderArr && medOrderArr.length > 0) {
				let domValue = this.handleRuleReference(medOrderArr, ruleOfReferences ? ruleOfReferences : 'ordMedItemDesc');
				ctl.SetElementTextByID(medicalOrderData.fieldID, domValue, medicalOrderData?.recordDOMID || '');
				this.setState({ medicalOrderVisible: false });
			} else {
				message.error('请勾选或者录入医嘱再进行插入。');
			}
		}
	}

	// 判断文件内容是否修改
	getModified = () => {
		let { isOperable, isModifyPermissions } = this.state;
		let params = this.props.param ? this.props.param : {};
		var ctl = document.getElementById(this.editorID);
		let isModify = ctl && ctl.getModified && ctl.getModified(true);
		return isModify && isOperable === 'N' && (isModifyPermissions === 'Y' || !params.isDelete);
	}

	// 设置病历修改状态
	resetModified = (isSave) => {
		var ctl = document.getElementById(this.editorID);
		ctl && ctl.resetModified && ctl.resetModified(true);
		if (isSave !== 'noPage') {
			let pageNum = ctl && ctl.GetDocumentPageNum && ctl.GetDocumentPageNum(); // 获取病历模板总页数
			// console.log(pageNum)
			this.setState({ pageNum });
		}
		if (isSave === 'noSave') { // 是否可以操作保存及删除等按钮
			this.setState({ isOperable: 'Y' });
		}
		if (isSave === 'isModifyPermissions') {
			this.setState({ isModifyPermissions: 'Y', saveBtnLoading: false })
		}
		if (isSave === 'clearSaveBtnLoading') {
			this.setState({ saveBtnLoading: false })
		}
	}

	// 右击自定义右键菜单
	mySetContextMenu = () => {
		const { courseOfDiseaseFlag } = this.state;
		var ctl = document.getElementById(this.editorID);
		var jsonMenu = [{
			label: '全选(Ctrl + a)',
			cmdName: 'selectall'
		}, {
			cmdName: 'copy'
		}, {
			label: '粘贴(Ctrl + v)',
			cmdName: 'paste',
			exec: () => this.handlPaste('N')
		}, '-', {
			label: '查找替换',
			cmdName: 'findReplace',
			exec: this.handlFindReplace
		},
		{
			label: '同步到其他模板',
			cmdName: 'asyncXML',
			exec: this.handleSynchronizeXML
		}
			// {
			// 	label: '粘贴(带格式)',
			// 	cmdName: 'paste',
			// 	exec: () => this.handlPaste('Y')
			// }
		];
		if (courseOfDiseaseFlag === 'Y') { // 病程
			jsonMenu.push({
				label: '病程单独页标志',
				cmdName: 'newPage',
				exec: this.handleModifyNewPage
			});
		}
		ctl && ctl.SetContextMenu && ctl.SetContextMenu(jsonMenu);
	}

	// 查找替换
	handlFindReplace = () => {
		this.findReplaceRef && this.findReplaceRef.modifyVisible(true);
	}

	// 保留格式粘贴
	handlPaste = (pasteFormat) => {
		this.setState({ pasteFormat }, () => {
			this.handleCompile(5)
		})
	}

	// 关闭历史知识库引用弹窗
	handleHistoricalKnowledgeBaseCancel = () => {
		this.setState({ historicalKnowledgeBase: false })
	}

	// 确认引用
	handleHistoricalKnowledgeBaseOk = () => {
		console.log('确认引用')
	}

	// tabs切换
	handleTabsCallback = (key) => {
		this.setState({ activeTabs: key })
	}

	// 根据fildID插入xml
	handleInsertXmlById = () => {
		var ctl = document.getElementById(this.editorID);
		let xml = '<XTextDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" EditorVersionString="1.2019.1.29"><Attributes /><AutoFixTextMode>None</AutoFixTextMode><XElements><Element xsi:type="XTextHeader"><Attributes /><AutoFixTextMode>None</AutoFixTextMode><AcceptTab>true</AcceptTab><XElements><Element xsi:type="XParagraphFlag" StyleIndex="0" /></XElements></Element><Element xsi:type="XTextBody"><Attributes /><AutoFixTextMode>None</AutoFixTextMode><AcceptTab>true</AcceptTab><XElements><Element xsi:type="XString" StyleIndex="1"><AutoFixTextMode>None</AutoFixTextMode><XElements xsi:nil="true" /><Text>右眼红、痛伴视力渐下降10余天</Text></Element></XElements></Element><Element xsi:type="XTextFooter"><Attributes /><AutoFixTextMode>None</AutoFixTextMode><AcceptTab>true</AcceptTab><XElements /></Element></XElements><Parameters /><FileName>C:\\Users\\DC\\Desktop\\xmlContent.xml</FileName><FileFormat>XML</FileFormat><UserHistories /><ContentStyles><Default xsi:type="DocumentContentStyle"><FontName>宋体</FontName><FontSize>12</FontSize></Default><Styles><Style Index="0"><FontName>宋体</FontName><FontSize>12</FontSize><Align>Center</Align></Style><Style Index="1"><BackgroundColor>#00000000</BackgroundColor><FontName>宋体</FontName><FontSize>11</FontSize></Style></Styles></ContentStyles><RepeatedImages /><ControlOptionsForDebug><RuleVisible>false</RuleVisible><UserInfo><ID>511</ID><Name>上官海燕</Name><PermissionLevel>0</PermissionLevel></UserInfo><DocumentOptions><SecurityOptions><AutoEnablePermissionWhenUserLogin>false</AutoEnablePermissionWhenUserLogin><TrackVisibleLevel0><UnderLineColorString>#ADD8E6</UnderLineColorString><DeleteLineColorString>#FF7F50</DeleteLineColorString></TrackVisibleLevel0><TrackVisibleLevel1 /><TrackVisibleLevel2><BackgroundColorString>#FFFFE0</BackgroundColorString><UnderLineColorNum>2</UnderLineColorNum><DeleteLineNum>2</DeleteLineNum></TrackVisibleLevel2><TrackVisibleLevel3><BackgroundColorString>#FFFFE0</BackgroundColorString><UnderLineColorNum>2</UnderLineColorNum><DeleteLineNum>2</DeleteLineNum></TrackVisibleLevel3></SecurityOptions><ViewOptions><NewInputContentUnderlineColor /><NewInputContentUnderlineColorValue>#00000000</NewInputContentUnderlineColorValue><AdornTextBackColorValue>#64808080</AdornTextBackColorValue><FieldHoverBackColorValue>#FFFFFF</FieldHoverBackColorValue><TagColorForNormalFieldValue>#FF0000</TagColorForNormalFieldValue></ViewOptions><BehaviorOptions><ParagraphFlagFollowTableOrSection>true</ParagraphFlagFollowTableOrSection><ValidateUserIDWhenEditDeleteComment>true</ValidateUserIDWhenEditDeleteComment><InsertDocumentWithCheckMRID>PromptForbitWhenFail</InsertDocumentWithCheckMRID></BehaviorOptions><EditOptions><GridLinePreviewText>DCWriter是南京都昌信息科技有限公司自主研发的专业的电子病历文档编辑器。</GridLinePreviewText></EditOptions></DocumentOptions><Font><Size>12</Size></Font><HeaderFooterFlagVisible>None</HeaderFooterFlagVisible><JumpPrint /><PageTitlePosition>BottomRight</PageTitlePosition><Readonly>true</Readonly></ControlOptionsForDebug><GlobalJavaScriptReferences /><Info><LicenseText>本软件未注册。</LicenseText><CreationTime>1980-01-01T00:00:00</CreationTime><LastModifiedTime>2020-12-31T13:37:29.8853848+08:00</LastModifiedTime><LastPrintTime>1980-01-01T00:00:00</LastPrintTime><Operator>DCSoft.Writer Version:1.2020.7.3</Operator><NumOfPage>1</NumOfPage></Info><BodyText>右眼红、痛伴视力渐下降10余天</BodyText><Comments /><LocalConfig /><PageSettings /></XTextDocument>';;
		var obj = {
			"file": xml,//xml文档
			"format": "xml",//xml文档格式
			"base64": "false",//是否是base64字符串
			"type": "two",
			"position": "start"
		}
		ctl.InsertXmlById(obj, "basic100125");
	}

	// 内容变更
	handleContentChangeVisiblehCancel = () => {
		this.setState({ contentChangeVisible: false })
	}

	// 确定更新
	handleContentChangeVisiblehOk = () => {
		var ctl = document.getElementById(this.editorID);
		let contentChangSelectedRows = JSON.parse(JSON.stringify(this.state.contentChangSelectedRows));
		if (contentChangSelectedRows && contentChangSelectedRows.length > 0) {
			const recordsArr = ctl && ctl.GetCourseRecords && ctl.GetCourseRecords();
			for (var i = 0; i < contentChangSelectedRows.length; i++) {
				let displayValue = contentChangSelectedRows[i]?.displayValue || '';
				let fieldID = contentChangSelectedRows[i]?.fieldID || '';
				let recordID = contentChangSelectedRows[i]?.recordID || '';
				if (fieldID) {
					if (recordID && recordsArr && recordsArr.length > 0) {
						for (let j = 0; j < recordsArr.length; j++) {
							let currentElementID = recordsArr[j] && recordsArr[j].ElementID ? recordsArr[j].ElementID : '';
							currentElementID = currentElementID.indexOf('record') > -1 || currentElementID.indexOf('paging') > -1 ? currentElementID.slice(6) : currentElementID;
							if (currentElementID && currentElementID === recordID) {
								ctl.SetElementTextByID(fieldID, displayValue, recordsArr[j].ElementID);
								break;
							}
						}
					} else {
						if (fieldID && (fieldID.slice(0, 5) === 'table')) { // 表格渲染
							let displayValueArr = contentChangSelectedRows[i]?.displayValueArr || '';
							this.handleTableAssignment(fieldID, displayValueArr);
							continue;
						} else {
							ctl.SetElementTextByID(fieldID, displayValue);
							continue;
						}
					}
				}
			}
			this.setState({ contentChangeSelectedRowKeys: [], contentChangSelectedRows: [] }, () => {
				this.handleContentChangeVisiblehCancel();
			})
		} else {
			message.info("请选择需要更新的数据。")
		}
	}

	// 获取内容更新提示列表数据
	handleShowContentChangeModal = () => {
		this.setState({ contentChangeVisible: true })
	}

	// 修改病历权限
	handleModify = () => {
		this.setState({ isModifyPermissions: "Y" }, () => {
			this.handleModeSwitching()
		})
	}

	// 模式切换
	handleModeSwitching = () => {
		let { fileName, isClear } = this.state;
		this.AjaxLoad(fileName, isClear, '', '', true)
	}

	// 锚点定位 - 跳转到相对应的病程位置
	handleAnchorPositioning = (ID) => {
		ID = ID ? String(ID) : '';
		let { isModifyPermissions } = this.state;
		let params = this.props.param ? this.props.param : {};
		var ctl = document.getElementById(this.editorID);
		if (isModifyPermissions === 'N' && params.isDelete) {
			// 预览模式下实现病程定位
			let navigatorArr = document.WriterControl.getNavigator();
			if (navigatorArr && navigatorArr.length > 0) {
				for (var j = 0; j < navigatorArr.length; j++) {
					let currentAnchorID = navigatorArr[j].Element && navigatorArr[j].Element.id ? navigatorArr[j].Element.id : '';
					if (currentAnchorID && (currentAnchorID.slice(6) === (ID && (ID.indexOf('record') > -1 || ID.indexOf('paging') > -1) ? ID.slice(6) : ID))) {
						// 将视图滚动到可见区域
						navigatorArr[j].Element && navigatorArr[j].Element.scrollIntoView && navigatorArr[j].Element.scrollIntoView(true);
						break;
					}
				}
			}
		} else {	// 书写模式病程记录定位
			let btrPrintPreview = document.getElementById(this.editorID + 'btrPrintPreview');
			btrPrintPreview ? btrPrintPreview.style.display = 'none' : '';
			// 获取所有病程
			var recordsArr = ctl && ctl.GetCourseRecords && ctl.GetCourseRecords();
			console.log('recordsArr', recordsArr)
			if (recordsArr && recordsArr.length > 0) {
				for (var i = 0; i < recordsArr.length; i++) {
					let currentAnchorID = recordsArr[i]?.ElementID || '';
					if (currentAnchorID && (currentAnchorID.slice(6) === (ID && (ID.indexOf('record') > -1 || ID.indexOf('paging') > -1) ? ID.slice(6) : ID))) {
						recordsArr[i].Select();
						break;
					}
				}
			}
		}
	}

	// 病程读写控制 - 不做单独病程控制
	readingAndWritingControlOfDiseaseCourse = (mode) => {
		setTimeout(() => {
			this.resetModified('noPage'); // 设置病历修改状态
		}, 300)
	}

	// 设置输入域是否可编辑 type等于id则为当前病历输入域 不传则为病程
	setsWhetherTheInputFieldCanBeEdited = (element, disabled, type) => {
		// console.log(element, disabled, type)
		var ctl = document.getElementById(this.editorID);
		var dom = ctl && ctl.GetContentDocument && ctl.GetContentDocument() && ctl.GetContentDocument().getElementById && ctl.GetContentDocument().getElementById(element);
		if (type === 'id') { // 根据输入域id设置是否只读
			if (dom && dom.setAttribute) {
				// if (element === 'field334') { // 根据filedID除去输入域某个属性
				// 	dom.removeAttribute('dc_specifywidth');
				// }
				dom.setAttribute('contenteditable', disabled); //只读
				dom.setAttribute('dc_deleteable', disabled); //不可删除
				// dom.setAttribute('dc_contentreadonly', 'Inherit'); //只读 contenteditable 这样只是在前端临时锁死，后来不会将你锁死的状态给保存下来
				// dom.removeAttribute('dc_contentreadonly')
				dom.style.pointerEvents = disabled === 'True' ? 'auto' : 'none';
				dom.style.backgroundColor = disabled === 'True' ? '#fff' : '#f5f5f5';
				return;
			}
		}
		let recordsInput = $(dom).find('[dctype="XTextInputFieldElement"]'); // 获取每个病程下面的输入域
		for (var i = 0; i < recordsInput.length; i++) {
			if (recordsInput[i] && recordsInput[i].setAttribute) {
				recordsInput[i].setAttribute('contenteditable', disabled); //只读
				recordsInput[i].setAttribute('dc_deleteable', disabled); //不可删除
				// recordsInput[i].setAttribute('dc_contentreadonly', 'Inherit'); //只读 
				// recordsInput[i].removeAttribute('dc_contentreadonly')
				recordsInput[i].style.pointerEvents = disabled === 'True' ? 'auto' : 'none';
				recordsInput[i].style.backgroundColor = disabled === 'True' ? '#fff' : '#f5f5f5';
			}
		}
	}

	// 强制解锁
	updateMedicalRecordLockStatus = () => {
		this.setState({ forceUnlock: "Y" }, () => {
			this.props && this.props.updateMedicalRecordLockStatus && this.props.updateMedicalRecordLockStatus()
		})
	}

	// DRG审核
	handleDRGAudit = async () => {
		try {
			const { recordData, templateParams } = this.state;
			let data = {
				params: [{
					patEMRRecordID: templateParams?.BSEMRRDParRef || templateParams.patEMRRecordID || templateParams.ID || '',
					admID: recordData && recordData.admID ? recordData.admID : ''
				}]
			}
			let res = await React.$asyncPost(this, '05900006', data);
			let DRGUrl = res.result?.url || '';
			if (DRGUrl) {
				this.setState({ DRGVisible: true, DRGUrl });
			} else {
				message.error('DRG审核返回链接路径异常，请稍后重试！')
			}
		} catch (error) {
			console.log(error);
		}
	}

	// 查找内容
	handleSearchText = (searchText) => {
		if (typeof (searchText) !== 'string') {
			return false;
		}
		var ctl = document.getElementById(this.editorID);
		var doc = ctl && ctl.GetContentDocument && ctl.GetContentDocument();
		var win = ctl && ctl.GetContentWindow && ctl.GetContentWindow(true);
		if (ctl && win.find) {
			ctl.FocusAdjacent('beforebegin', doc.body);
			var result = [];
			while (win.find(searchText) == true) {
				var obj = {};
				var range = win.uiEditor.selection.getRange();
				obj.Range = range.cloneRange();
				// 选中方法
				obj.select = function () {
					if (this.Range) {
						this.Range.select();
						var startContainer = this.Range.startContainer;
						if (startContainer) {
							if (startContainer.nodeName == '#text') {
								startContainer = startContainer.parentNode || startContainer.parentElement;
							}
							var zoomNum = isNaN(parseFloat($(doc.body).css('zoom'))) ? 1 : parseFloat($(doc.body).css('zoom'));
							if (doc.body.getAttribute('browser') == 'FireFox') {
								zoomNum = 1;
							}
							var _top = win.DCDomTools.GetViewTopInDocument(startContainer);
							$(doc.body).scrollTop(_top * zoomNum);
						}
					}
				}
				// 正在搜索的文本
				obj.searchText = searchText;
				result.push(obj);
			}
			ctl.FocusAdjacent('beforebegin', doc.body);
			return result;
		}
	}

	// 替换文字
	handleReplaceText = (searchText, replaceText) => {
		if (typeof (searchText) !== 'string') {
			return false;
		}
		var ctl = document.getElementById(this.editorID);
		var doc = ctl && ctl.GetContentDocument && ctl.GetContentDocument();
		// var nodeDiv = doc.getElementById('dcGlobalRootElement')
		// var allChildNodes = function (node, type) {
		// 	// 1.创建全部节点的数组
		// 	var allCN = [];
		// 	// 2.递归获取全部节点
		// 	var getAllChildNodes = function (node, type, allCN) {
		// 		// 获取当前元素所有的子节点nodes
		// 		var nodes = node.childNodes;
		// 		console.log(nodes)
		// 		// 获取nodes的子节点
		// 		for (var i = 0; i < nodes.length; i++) {
		// 			var child = nodes[i];
		// 			// 判断是否为指定类型节点
		// 			if (child.nodeType == type) {
		// 				allCN.push(child);
		// 			}
		// 			getAllChildNodes(child, type, allCN);
		// 		}
		// 	}
		// 	getAllChildNodes(node, type, allCN);
		// 	// 3.返回全部节点的数组
		// 	return allCN;
		// }
		// var allTextNode = allChildNodes(nodeDiv, 3);
		var allTextNode = $(doc).find("[dctype='XTextInputFieldElement']"); //JQUERY
		let replaceNode = [];
		for (var i = 0; i < allTextNode.length; i++) {
			let contetnSpan = allTextNode[i] && allTextNode[i].children && allTextNode[i].children.length > 2 ? allTextNode[i].children[1] : '';
			let currentVal = contetnSpan?.innerText || '';
			if (typeof (replaceText) === 'string' && typeof (currentVal) === 'string' && currentVal.indexOf(searchText) > -1) {
				var regexp = new RegExp(searchText, 'g');
				replaceNode.push(allTextNode[i]);
				if (contetnSpan) {
					contetnSpan.innerHTML = currentVal?.replace(regexp, replaceText);
				}
			}
		}
		return replaceNode;
	}

	handleSyncNoticeChange = (e) => {
		this.setState({ syncNotice: e.target.checked })
	}

	// 同步当前xml内容到其他模板 - 同步到其他模板
	handleSynchronizeXML = () => {
		let { isOperable } = this.state;
		if (isOperable !== 'N') {
			message.error('当前病历未保存，没有需要同步的数据！');
			return;
		}
		let detailListFlag = React.$getLocalStorageData('EMR_syncNotice', false);
		if (detailListFlag !== 'Y') {
			confirm({
				title: '同步须知',
				content: (<div>
					<div style={{ marginBottom: '6px' }}>同步时打开了其他病历会导致数据同步到其他病历失败，是否继续同步？</div>
					<Checkbox onChange={this.handleSyncNoticeChange}>不再提醒</Checkbox>
				</div>),
				okText: '是->继续同步',
				cancelText: '否->先不同步',
				onOk: () => {
					this.handleConfirmSync();
				},
				onCancel: () => { }
			});
		} else {
			this.handleConfirmSync();
		}
	}

	handleConfirmSync = () => {
		let isModify = this.getModified();
		if (isModify) {
			confirm({
				title: <div>当前病历已修改，是否需要保存后再同步？</div>,
				okText: '是->保存后同步',
				cancelText: '否->直接同步',
				onOk: () => {
					let record = {
						saveType: 'print'
					};
					this.props.handleSave && this.props.handleSave('saveBeforePrinting', record, this.handleShowSyncModal); // 保存后执行回调函数
				},
				onCancel: () => {
					this.handleShowSyncModal();
				},
			});
		} else {
			this.handleShowSyncModal();
		}
	}

	handleShowSyncModal = Util.debounce(() => {
		const { recordData, templateParams, syncNotice } = this.state;
		// console.log('syncNotice', syncNotice)
		React.$setLocalStorageData('EMR_syncNotice', syncNotice ? 'Y' : 'N', false);
		this.updateTemplateRef && this.updateTemplateRef.modifyVisible(true, {
			patEMRRecordID: templateParams?.BSEMRRDParRef || templateParams.patEMRRecordID || templateParams.ID || '',
			admID: recordData && recordData.admID ? recordData.admID : ''
		});
	})

	beforeUpload = (file) => {
		const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
		if (!isJpgOrPng) {
			message.error('图片格式不正确!');
		}
		return isJpgOrPng;
	}

	getBase64 = (img, callback) => {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result));
		reader.readAsDataURL(img);
	}

	// 图片上传change事件
	handleUploadChange = (info) => {
		if (info.file.status === 'uploading') {
			this.setState({ uploadBtnLoading: true });
			return;
		}
		let ctl = document.getElementById(this.editorID);
		let currentDom = ctl.CurrentInputField();
		this.setState({ uploadBtnLoading: false });
		// console.log('currentDom', currentDom)
		if (currentDom) {
			this.getBase64(info.file.originFileObj, imageUrl => {
				currentDom.innerHTML = '<img src="' + imageUrl + '" width="80px" height="80px"/>'
			});
		} else {
			message.error('请确认光标在是否在您想插入的输入域中!');
		}
	}

	// 判断是否为空模板
	handleDetermineTemplateContent = () => {
		let ctl = document.getElementById(this.editorID);
		let WCDoc = ctl?.GetContentDocument() || '';
		let WCBodyChildP = WCDoc?.getElementById('divDocumentBody_0')?.getElementsByTagName('p') || '';
		// console.log('WCBodyChildP', WCBodyChildP)
		let isEmptyTemplate = 'Y';
		if (!(WCBodyChildP && ((WCBodyChildP.length === 1 && 'innerHTML' in WCBodyChildP[0] && (WCBodyChildP[0].innerHTML === '' || WCBodyChildP[0].innerHTML === '<br>' || WCBodyChildP[0].innerHTML === `<br dcignore=\"1\">` || WCBodyChildP[0].innerHTML.length < 50)) || WCBodyChildP.length < 1))) {
			isEmptyTemplate = 'N';
		}
		return isEmptyTemplate;
	}

	// 保存
	handleEMRSave = () => {
		const { saveBtnLoading } = this.state;
		if (saveBtnLoading) return;
		this.setState({ saveBtnLoading: true }, () => {
			if (this.handleDetermineTemplateContent() === 'Y') {
				message.error('当前病历加载异常不支持保存！可双击病历树重新加载该病历');
				this.setState({ saveBtnLoading: false });
				return;
			}
			const { isOperable } = this.state;
			let isModify = this.getModified();
			let params = this.props.param ? this.props.param : {};
			if (!isModify && isOperable === 'N' && params.isDelete) {
				message.error('当前病历数据未发生变动，不需要保存！');
				this.setState({ saveBtnLoading: false });
				return;
			}
			this.props.handleSave && this.props.handleSave();
		})
	}

	// 另存为范例病例
	handleExampleTemplate = () => {
		let ctl = document.getElementById(this.editorID);
		const xmlStr = ctl?.SaveDocumentToString('XML');
		this.props.handleExampleTemplate && this.props.handleExampleTemplate({ xml: xmlStr });
	}

	// 病程单独页打印
	handleModifyNewPage = () => {
		let ctl = document.getElementById(this.editorID);
		let myHtml = ctl.GetContentDocument();
		let myDiv = myHtml.querySelectorAll("div[dctype='XTextSubDocumentElement']");
		let $box = $(ctl.DocumentSelection().currentContainer.parentElement).parents("div[dctype='XTextSubDocumentElement']"); // 获取光标所在的子病程div
		let isExistence = false;
		let defaultNewPage = false;
		let dc_title = '';
		for (let i = 0; i < myDiv.length; i++) {
			if (myDiv[i] == $box[0]) {
				isExistence = true;
				defaultNewPage = myDiv[i]?.getAttribute('dc_newpage');
				dc_title = myDiv[i]?.getAttribute('dc_title');
				break;
			}
		}
		if (isExistence) {
			this.setState({ newPageRowData: { id: $box[0]?.id || '', newPageFlag: defaultNewPage === 'true' ? 'Y' : 'N', title: dc_title } }, () => {
				this.newPageModalRef && this.newPageModalRef.modifyVisible(true)
			});
		} else {
			message.error("请将光标定位到病程任意一个输入域！");
		}
	}

	// 保存病程分页标志
	handleNewPageSave = (values) => {
		try {
			const { newPageRowData } = this.state;
			let ctl = document.getElementById(this.editorID);
			let myHtml = ctl.GetContentDocument();
			let myDiv = myHtml.querySelectorAll("div[dctype='XTextSubDocumentElement']");
			for (let i = 0; i < myDiv.length; i++) {
				if (myDiv[i]?.id == newPageRowData?.id) {
					myDiv[i].setAttribute('dc_newpage', values?.newPageFlag === 'Y' ? 'true' : 'false');
					break;
				}
			}
			this.newPageModalRef && this.newPageModalRef.modifyVisible(false);
			this.props.handleSave && this.props.handleSave();
		} catch (error) {
			console.log(error);
		}
	}

	// 行间距
	handleLineSpaceChange = e => {
		var ctl = document.getElementById(this.editorID);
		ctl.DCExecuteCommand('lineheight', true, e);
		this.setState({ lineSpace: undefined });
	}

	render() {
		let { userData, isColorPickup, fontColor, top, left, visible, modalSelectedKeys, customDataSet, isOperable, operableWidth, templateErrorMes, courseOfDiseaseVisible, saveBtnLoading, templateID, DRGVisible, DRGUrl,
			courseOfDiseaseValue, templateSelectData, dropDownSearch, columns, selectDesc, selectRowData, modalTableData, modalTotal, modalPage, modalLoading, forcedPageChange, printSpecifiedPage,
			customDataTableData, diagnosisSearch, historicalKnowledgeBase, activeTabs, contentChangeVisible, contentChangeTableData, contentChangeSelectedRowKeys, contentChangSelectedRows,
			isModifyPermissions, isPrintPreview, medicalOrderVisible, courseOfDiseaseFlag, courseOfDiseaseLoading, newPageFormData, newPageRowData, scaleZoom, lineSpace
		} = this.state;
		let params = this.props.param ? this.props.param : {};
		// 卡类型
		let templateSelectOption = templateSelectData && templateSelectData.map((item, index) => {
			return (<Option key={index} value={item.newestVersionID} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		let downLoadFile = (
			<Menu className='personage-menu'>
				<Menu.Item><span onClick={() => this.DownLoadFile('PDF')}>PDF</span></Menu.Item>
				<Menu.Item><span onClick={() => this.DownLoadFile('xml')}>XML</span></Menu.Item>
				<Menu.Item><span onClick={() => this.DownLoadFile('RTF')}>RTF</span></Menu.Item>
				<Menu.Item><span onClick={() => this.DownLoadFile('txt')}>TXT</span></Menu.Item>
				<Menu.Item><span onClick={() => this.DownLoadFile('longimg')}>Longimg</span></Menu.Item>
			</Menu>
		)

		// 组件所需参数
		const tableParam = {
			// 表头配置
			columns: columns && columns.length > 0 ? columns : this.columns,
			// 表格数据
			data: modalTableData,
			// 数据总条数
			total: modalTotal,
			// 当前页数
			page: modalPage,
			pageSize: "20",
			// 表格的宽度
			x: 500,
			y: 255,
			height: '300px',
			isOnRow: true,
			rowClassName: true,
			loading: modalLoading,
			TableClassName: 'modal-select',
		};

		// 内容更新提示列表列选择
		const contentChangeRowSelection = {
			selectedRowKeys: contentChangeSelectedRowKeys,
			selectedRows: contentChangSelectedRows,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({ contentChangeSelectedRowKeys: selectedRowKeys, contentChangSelectedRows: selectedRows })
			},
		};

		return (
			<div className="electronic-case-template">
				{params?.viewEMRFlag === 'Y' ? ( // 查看病历
					<div className="operation-span" style={{ textAlign: 'right' }}>
						<Button
							ghost
							size="small"
							type="primary"
							onClick={this.PrintDocument}
						>
							打印
						</Button>
						<Button
							size="small"
							type="primary"
							style={{ marginLeft: '12px' }}
							onClick={this.OpenPreview}
						>
							{this.setMessage("ElectronicCaseTemplatePrinting_preview", "descripts", "打印预览")}
						</Button>
					</div>
				) : ( // 书写|模板
					<>
						{!params.isBasicOperation ? <div className="operation-span">
							{params.isNewFile ? <span onClick={this.NewFile}>
								<Icon type="plus" />
								{this.setMessage("ElectronicCaseTemplateNew", "descripts", "新建")}
							</span> : ''}
							{!params.isRevoke ? <span onClick={() => this.handleCompile(1)}>
								<Icon type="reload" style={{ transform: "rotateY(-180deg)" }} />
								{this.setMessage("ElectronicCaseTemplateRevoke", "descripts", "撤销")}
							</span> : ''}
							{!params.isRedo ? <span onClick={() => this.handleCompile(2)} title={this.setMessage("ElectronicCaseTemplateRedo", "message", "重复上一步操作")}>
								<Icon type="reload" />
								{this.setMessage("ElectronicCaseTemplateRedo", "descripts", "重做")}
							</span> : ''}
							{!params.isCopy ? <span onClick={() => this.handleCompile(3)}>
								<Icon type="copy" />
								{this.setMessage("ElectronicCaseTemplateCopy", "descripts", "复制")}
							</span> : ''}
							{!params.isShear ? <span onClick={() => this.handleCompile(4)}>
								<Icon type="scissor" />
								{this.setMessage("ElectronicCaseTemplateCut", "descripts", "剪切")}
							</span> : ''}
							{!params.isPaste ?
								<Tooltip title="粘贴贴只能对编辑器内部复制的内容进行粘贴，编辑器之外复制的内容必须使用Ctrl+V进行粘贴。">
									<span onClick={() => this.handleCompile(5)}>
										<Icon type="snippets" />
										{this.setMessage("ElectronicCaseTemplatePaste", "descripts", "粘贴")}
									</span>
								</Tooltip> : ''}
							{!params.isClearFormat ? <span onClick={() => this.handleFont(4)}>
								<Icon type="radius-setting" />
								{this.setMessage("ElectronicCaseTemplateClear_format", "descripts", "清除格式")}
							</span> : ''}
							{!params.isAllElection ? <span onClick={() => this.handleCompile(7)}>
								<Icon type="check" />
								{this.setMessage("ElectronicCaseTemplateSelect_all", "descripts", "全选")}
							</span> : ''}
							{!params.isSaveAnother ? <Dropdown overlay={downLoadFile}>
								<span>
									<Icon type="download" />
									{this.setMessage("ElectronicCaseTemplateSave_as", "descripts", "另存为")}
								</span>
							</Dropdown> : ''}
							{this.props.handleExampleTemplate ? <span onClick={this.handleExampleTemplate}>
								<Icon type="file-add" />
								{this.setMessage("ElectronicCaseTemplateExample_template", "descripts", "另存为范例模板")}
							</span> : ''}
							<span>
								<Select
									size="small"
									style={{ width: '76px', marginRight: '6px' }}
									placeholder="缩放"
									disabled={!(isModifyPermissions === 'Y' || !params.isDelete)}
									value={scaleZoom}
									onChange={this.scaleEditorPage}
								>
									<Option value="0.75">75%</Option>
									<Option value="1">正常</Option>
									<Option value="1.25">125%</Option>
									<Option value="1.5">150%</Option>
									<Option value="1.75">175%</Option>
									<Option value="2">200%</Option>
								</Select>
								<Select
									allowClear
									size="small"
									placeholder="行间距"
									style={{ width: '84px', marginRight: '6px' }}
									value={lineSpace}
									onChange={this.handleLineSpaceChange}
								>
									<Option value="1.0">1.0</Option>
									<Option value="1.15">1.15</Option>
									<Option value="1.5">1.5</Option>
									<Option value="2.0">2.0</Option>
									<Option value="2.5">2.5</Option>
									<Option value="3.0">3.0</Option>
								</Select>
								<Select size="small" onChange={this.setFontSize} value={this.state.fontSize} style={{ width: '70px' }} placeholder="字号">
									{/* <Option value="6.7px">八号</Option>
							<Option value="7.3px">七号</Option>
							<Option value="8.7px">小六</Option>
							<Option value="10px">六号</Option> */}
									<Option value="12px">小五</Option>
									<Option value="14px">五号</Option>
									<Option value="16px">小四</Option>
									<Option value="18.7px">四号</Option>
									<Option value="20px">小三</Option>
									<Option value="21.3px">三号</Option>
									<Option value="24px">小二</Option>
									<Option value="29.3px">二号</Option>
									<Option value="32px">小一</Option>
									<Option value="34.7px">一号</Option>
									<Option value="48px">小初</Option>
									<Option value="56px">初号</Option>
									<Option value="71.7px">特号</Option>
									<Option value="83.7px">大特号</Option>
									<Option value="95.6px">1英寸</Option>
								</Select>
							</span>
							<div className="its-way" style={{ display: "inline-block" }}>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateBold", "descripts", "加粗")}>
									<Icon type="bold" onClick={() => this.handleFont(5)} />
								</Tooltip>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateTilt", "descripts", "倾斜")}>
									<Icon type="italic" onClick={() => this.handleFont(6)} />
								</Tooltip>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateUnderline", "descripts", "下划线")}>
									<Icon type="underline" onClick={() => this.handleFont(7)} />
								</Tooltip>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateStrikethrough", "descripts", "删除线")}>
									<Icon type="strikethrough" onClick={() => this.handleFont(8)} />
								</Tooltip>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateFont_color", "descripts", "字体色")}>
									<Icon type="font-colors" onClick={() => this.handleShowColorTemplate(this.editorID + "font-color-icon")} id={this.editorID + "font-color-icon"} />
								</Tooltip>
								<Tooltip title={this.setMessage("ElectronicCaseTemplateBackground_color", "descripts", "背景色")}>
									<Icon type="bg-colors" onClick={() => this.handleShowColorTemplate(this.editorID + "bg-color-icon")} id={this.editorID + "bg-color-icon"} />
								</Tooltip>
								<ColorPickup
									top={top}
									left={left}
									visible={isColorPickup}
									color={fontColor}
									onChange={this.handleColorChange}
									cancelColorPickup={this.cancelColorPickup} />
								{isOperable === 'N' ? (
									<Upload
										showUploadList={false}
										accept="image/png, image/jpg, image/jpeg, image/gif"
										onChange={this.handleUploadChange}
										beforeUpload={this.beforeUpload}
									>
										<Tooltip title="插入提醒：请先选择需要插入的位置!">
											<Icon type="picture" />
										</Tooltip>
									</Upload>
								) : ''}
							</div>
							{!params.isSetTemplateSize ? <span onClick={this.documentSizeSettings}>
								<Icon type="font-size" />
								{this.setMessage("ElectronicCaseTemplateTemplate_size", "descripts", "模板大小")}
							</span> : ''}
							{params.isReload ? <span onClick={this.handleOnReload}>
								<Icon type="sync" />
								{this.setMessage("ElectronicCaseTemplateReload", "descripts", "重新加载")}
							</span> : ''}
							{params.self ? <span onClick={() => this.original(true)}>
								<Icon type="sync" />
								自适应
							</span> : ''}
							{params.original ? <span onClick={() => this.original(false)}>
								<Icon type="sync" />
								原始尺寸
							</span> : ''}
							<div style={{ display: "inline-block", float: 'right' }}>
								{params.prTing ? (
									(isModifyPermissions === 'N' && params.isDelete) || isPrintPreview === 'Y' ? (
										<Button
											style={{ marginRight: '5px' }}
											type="primary"
											onClick={this.PrintDocument}
										>
											打印
										</Button>
									) : (params.printDocument && isPrintPreview === 'N' ? (
										<Button
											onClick={this.OpenPreview}
											disabled={isOperable === 'N' && params.isDelete ? false : true}
											style={{ marginRight: '5px' }}
											type="primary"
										>
											{this.setMessage("ElectronicCaseTemplatePrinting_preview", "descripts", "打印预览")}
										</Button>
									) : '')
								) : ''}
								{/* 09/19处理，注释原因为撤销之后再次保存会产生两条记录，导致只能建一次的病历创建了两次 */}
								{/* {params.isHasDeletedRecord ? <Button type="primary" style={{ marginRight: '5px' }} onClick={this.props.undoDeleted} disabled={!params.isHasDeletedRecord}>
									{this.setMessage("ElectronicCaseTemplateUndoDelete", "descripts", "撤销删除")}
								</Button> : ''} */}
								{/* 验光单增加发送功能 */}
								{this.props.handleSend && templateID === '670' ? (
									<Button ghost type="primary" style={{ marginRight: '5px' }} disabled={!params.isDelete} onClick={this.props.handleSend}>
										{params?.sendTitle || '发送'}
									</Button>
								) : ''}
								{/* this.props.handleSave GetCourseRecordXML */}
								{!params.saveBtnFlag && (isModifyPermissions === "Y" || !params.isDelete) ? <Button type="primary" loading={saveBtnLoading} onClick={this.handleEMRSave} disabled={isOperable === "N" ? false : true}>
									{this.setMessage("ElectronicCaseTemplateSave", "descripts", "保存")}
								</Button> : ''}
								{isModifyPermissions === "N" && params.isDelete ? <Button type="primary" onClick={this.handleModify} disabled={isOperable === "N" ? false : true}>
									修改
								</Button> : ''}
								{this.props.handleRelease ? <Button type="primary" style={{ marginLeft: '5px' }} onClick={this.props.handleRelease} disabled={isOperable === "N" ? false : true}>
									{this.setMessage("ElectronicCaseTemplateRelease", "descripts", "发布")}
								</Button> : ''}
								{this.props.handleDelete && isModifyPermissions === "Y" ? <Popconfirm title="删除不可恢复，您确定要删除吗?" onConfirm={this.props.handleDelete}>
									<Button type="danger" style={{ marginLeft: '5px' }} disabled={(isOperable === "N" && params.isDelete) ? false : true}>
										{this.setMessage("ElectronicCaseTemplateDelete", "descripts", "删除")}
									</Button>
								</Popconfirm> : ''}
								{this.props.updateMedicalRecordLockStatus ? (params.isUnlocking || isOperable === "N" ? (
									<Button type="primary" ghost style={{ marginLeft: '5px' }} disabled>
										解锁
									</Button>
								) : (
									<Popconfirm title="强制解锁可能会造成正在填写该病历的医生数据丢失，您确定解锁吗？？？" onConfirm={this.updateMedicalRecordLockStatus}>
										<Button type="primary" ghost style={{ marginLeft: '5px' }}>
											解锁
										</Button>
									</Popconfirm>
								)) : ''}
							</div>
						</div> : ''}
						{params && params.prCont ? <div className="operation-span">
							{params && params.comments ? <span onClick={this.NewComment}>
								<Icon type="edit" />{this.setMessage("ElectronicCaseTemplateAnnotation", "descripts", "批注")}
							</span> : ''}
							<span onClick={this.handleSuperscript} title={this.setMessage("ElectronicCaseTemplateSuperscript", "message", "请选中内容操作")}>
								<Icon type="up-square" />
								{this.setMessage("ElectronicCaseTemplateSuperscript", "descripts", "上标")}
							</span>
							<span onClick={this.handleSubscript} title={this.setMessage("ElectronicCaseTemplateSubscript", "message", "请选中内容操作")}>
								<Icon type="down-square" />
								{this.setMessage("ElectronicCaseTemplateSubscript", "descripts", "下标")}
							</span>
							{courseOfDiseaseFlag === 'Y' ? <>
								<span onClick={this.courseOfDiseaseMoveUp}>
									病程上移
								</span>
								<span onClick={this.courseOfDiseaseMoveDown}>
									病程下移
								</span>
								<Popconfirm title="删除可能会导致数据丢失，您确定要删除吗?" onConfirm={this.removeCourseOfDisease}>
									<span style={{ color: "#ff4d4f" }}>
										删除病程
									</span>
								</Popconfirm>
								<span className="span" onClick={this.addCourseOfDisease}>
									新建病程
								</span>
							</> : ''}
							{contentChangeTableData && contentChangeTableData.length > 0 ? <span className="change-shadow" onClick={this.handleShowContentChangeModal}>
								有待更新数据
							</span> : ''}
							<Select
								mode="tags"
								size="small"
								allowClear
								value={printSpecifiedPage}
								placeholder={!(isOperable === 'N' && isPrintPreview === 'N' && params.isDelete) || (isModifyPermissions === 'N' && params.isDelete) || isPrintPreview === 'Y' ? (!(isOperable === 'N' && isPrintPreview === 'N' && params.isDelete) ? '不支持选择' : '不支持选择') : '指定页打印'}
								onChange={this.handlePrintSpecifiedPageChange}
								style={{ width: '120px', marginLeft: '6px', marginRight: '3px' }}
								disabled={!(isOperable === 'N' && isPrintPreview === 'N' && params.isDelete) || (isModifyPermissions === 'N' && params.isDelete) || isPrintPreview === 'Y' ? true : false}
							>
								{this.printSpecifiedPageOption()}
							</Select>
							<span>
								{/*  2023/08/14【注释isOperable === 'N', 没有权限的也需要可以打印】 */}
								<Button
									size="small"
									type="primary"
									disabled={!(isPrintPreview === 'N' && params.isDelete) ? true : false}
									onClick={() => this.handleSaveBeforePrinting(this.PrintDocument)}
								>
									打印
								</Button>
							</span>
							{params && params.addRow ?
								<Button
									size="small"
									type="primary"
									style={{ marginRight: '5px' }}
									onClick={this.addRow}
									disabled={isOperable === 'N' ? false : true}
								>添加行</Button>
								: ''}
							{params && params.addRow ?
								<Button
									size="small"
									type="danger"
									ghost
									style={{ marginRight: '5px' }}
									onClick={() => this.detailTable('Table_DeleteRow')}
									disabled={isOperable === 'N' ? false : true}
								>删除行</Button>
								: ''}
							{isModifyPermissions === 'Y' || !params.isDelete ? <Button
								size="small"
								type="primary"
								ghost
								style={{ marginRight: '5px' }}
								onClick={() => this.handleSaveBeforePrinting(this.OpenPreview)}
								disabled={isOperable === 'N' && isPrintPreview === 'N' && params.isDelete ? false : true}
							>打印预览</Button> : ''}
							{userData?.hospCode === 'H05' && templateID === '343' ? ( // 只有昆明老院并且是病案首页才有DRG审核
								<Button
									size="small"
									type="primary"
									ghost
									style={{ marginRight: '5px' }}
									onClick={this.handleDRGAudit}
									disabled={isOperable === 'N' && params.isDelete ? false : true}
								>DRG审核</Button>
							) : ''}
							{/* <Button style={{ marginRight: '5px', borderRadius: '50px', background: readNum === 3 ? '#1999db' : '#fff', color: readNum === 3 ? '#fff' : '#000' }} onClick={() => this.readNum(3)} >痕迹浏览模式</Button> */}
						</div> : ''}
						{!params.isFont ? <div style={{ paddingLeft: '12px' }}>
							<span onClick={() => this.handleCompile(6)} style={{ cursor: 'pointer' }}>
								<Icon type="highlight" />
								{this.setMessage('ElectronicCaseTemplateFormat_painter', 'descripts', '格式刷')}
							</span>
							<Select onChange={this.handleFontType} value={this.state.fontTyle} style={{ width: '120px', margin: '0 12px' }} placeholder={this.setMessage('ElectronicCaseTemplateFont', 'descripts', '字体')}>
								<Option value='SimSun'>宋体</Option>
								<Option value='SimHei'>黑体</Option>
								<Option value='Microsoft Yahei'>微软雅黑</Option>
								<Option value='Microsoft JhengHei'>微软正黑体</Option>
								<Option value='KaiTi'>楷体</Option>
								<Option value='NSimSun'>新宋体</Option>
								<Option value='FangSong'>仿宋</Option>
								<Option value='PingFang SC'>苹方</Option>
								<Option value='YouYuan'>幼圆</Option>
								<Option value='LiSu'>隶书</Option>
							</Select>
							<Select onChange={this.setFontSize} value={this.state.fontSize} style={{ width: '120px', marginRight: "12px" }} placeholder={this.setMessage('ElectronicCaseTemplateFont_size', 'descripts', '字体大小')}>
								<Option value='6.7px'>八号</Option>
								<Option value='7.3px'>七号</Option>
								<Option value='8.7px'>小六</Option>
								<Option value='10px'>六号</Option>
								<Option value='12px'>小五</Option>
								<Option value='14px'>五号</Option>
								<Option value='16px'>小四</Option>
								<Option value='18.7px'>四号</Option>
								<Option value='20px'>小三</Option>
								<Option value='21.3px'>三号</Option>
								<Option value='24px'>小二</Option>
								<Option value='29.3px'>二号</Option>
								<Option value='32px'>小一</Option>
								<Option value='34.7px'>一号</Option>
								<Option value='48px'>小初</Option>
								<Option value='56px'>初号</Option>
								<Option value='71.7px'>特号</Option>
								<Option value='83.7px'>大特号</Option>
								<Option value='95.6px'>1英寸</Option>
							</Select>
							<Divider type="vertical" />
							<span className="its-way" style={{ marginLeft: '12px' }}>
								<Icon type="align-left" title={this.setMessage('ElectronicCaseTemplateLeft_justify', 'descripts', '左对齐')} onClick={() => this.Indent(1)} />
								<Icon type="align-center" title={this.setMessage('ElectronicCaseTemplateCenter_aligned', 'descripts', '居中对齐')} onClick={() => this.Indent(2)} />
								<Icon type="align-right" title={this.setMessage('ElectronicCaseTemplateRight_justified', 'descripts', '右对齐')} onClick={() => this.Indent(3)} />
								<Icon type="menu-fold" title={this.setMessage('ElectronicCaseTemplateSegment_leading', 'descripts', '段前距')} onClick={() => this.Indent(8)} />
								<Icon type="menu-unfold" title={this.setMessage('ElectronicCaseTemplateBreakback_distance', 'descripts', '断后距')} onClick={() => this.Indent(9)} />
								<Icon type="ordered-list" title={this.setMessage('ElectronicCaseTemplateOrdered_list', 'descripts', '有序列表')} onClick={() => this.Indent(5)} />
								<Icon type="unordered-list" title={this.setMessage('ElectronicCaseTemplateUnordered_list', 'descripts', '无序列表')} onClick={() => this.Indent(6)} />
							</span>
						</div> : ''}
						{params && params.isInsert !== "hidden" ? <div className="insert-span operation-span">
							{this.setMessage("ElectronicCaseTemplateInsert", "descripts", "插入")}：
							<span onClick={() => this.insertInputField(3)}>{this.setMessage("ElectronicCaseTemplateInput_box", "descripts", "输入框")}</span>
							{params && params.setChapter === "show" ? <span onClick={this.handleSetChapter}>{this.setMessage("ElectronicCaseTemplateChapter_name", "descripts", "章节名称")}</span> : ''}
							<span onClick={() => this.clearChapterStyle(false)}>{this.setMessage("ElectronicCaseTemplateCannot_be_deleted", "descripts", "不可删")}</span>
							{/* <span onClick={this.handleFilterChapters}>过滤章节</span> */}
							<span onClick={() => this.insertInputField(2)}>{this.setMessage("ElectronicCaseTemplateDate", "descripts", "日期")}</span>
							<span onClick={this.MyInsertButtonInputField}>{this.setMessage("ElectronicCaseTemplateButton", "descripts", "按钮")}</span>
							<span onClick={this.NewComment}>{this.setMessage("ElectronicCaseTemplateAnnotation", "descripts", "批注")}</span>
							<span onClick={this.insertImage}>{this.setMessage("ElectronicCaseTemplateImage", "descripts", "图片")}</span>
							{/* <span onClick={this.clearCourseDiseaseStyle}>清除病程样式</span> */}
							{/* <span onClick={this.getSelectXML}>获取被选中的xml</span> */}
							{this.props.unlockingTemplate ? <span onClick={this.props.unlockingTemplate}>{this.setMessage("ElectronicCaseTemplateUnlock_template", "descripts", "解锁模板")}</span> : ''}
							{this.props.unlockKnowledgeBase ? <span onClick={this.props.unlockKnowledgeBase}>{this.setMessage("ElectronicCaseTemplateUnlock_KB", "descripts", "解锁知识库")}</span> : ''}
							{/* {!this.props.cursorPosition ? <span onClick={this.cursorPosition}>光标位置</span> : ''} */}
							{/* <span onClick={this.SetTableBorder}>去除表格边框</span> */}
							<span onClick={this.handleTableAssignment}>表格赋值</span>
						</div> : ''}
					</>
				)}
				<div className="layui-body" style={{
					height: params?.viewEMRFlag === 'Y' ? 'calc(100% - 34px)' : ( // 查看病历
						params && params.isInsert === 'hidden' ? (
							!params.isFont ? (
								params.isBasicOperation ? (params.prCont ? 'calc(100% - 102px)' : 'calc(100% - 68px)') : (params.prCont ? 'calc(100% - 68px)' : 'calc(100% - 34px)')
							) : (
								params.isBasicOperation ? (params.prCont ? 'calc(100% - 34px)' : '100%') : (params.prCont ? 'calc(100% - 68px)' : 'calc(100% - 34px)')
							)
						) : 'calc(100% - 107px)'),
					overflow: "hidden", position: 'relative', width: '100%'
				}}>
					<div style={{
						position: 'absolute', left: 0, right: "16px", bottom: 0, top: 0, margin: "0 auto", zIndex: 5, height: '100%', width: `calc(80px + ${operableWidth})`,
						display: "none"
						// display: isOperable === "N" && (isModifyPermissions === "Y" || !params.isDelete) ? "none" : "block"
					}}></div>
					{templateErrorMes ? <div style={{ color: "red", paddingTop: "12px", fontSize: "14px" }}>{templateErrorMes}</div> : <div
						// style={{width: '800px'}}
						id={this.editorID}
						style={{ height: '100%', overflow: "hidden" }}
						contentrendermode="NormalHtmlEditable" // 代表页面模式，比如：编辑模式：NormalHtmlEditable，打印预览模式：PagePreviewHtml。
						referencepathfordebug="ctlReference"
						workspacebackcolorstring="#B1CAEB" // 设置背景颜色
						// workspacebackgroundimage="Workspace-Background.png" // 设置背景图片
						// servicepageurl='http://www.dcwriter.cn:6788/ServicePage.aspx' //- 都昌测试服务
						servicepageurl={`${this.state.EMRIP}/DemoDocumentImageService.aspx`} // 是指向第一步建立的ASP.NET的WEB页面的路径，可以使用网络路径。
						useclassattribute="true"
						heightcompress="true"
						// backgroundtextoutputmode="Underline"    // 输入域在打印预览产生下划线
						backgroundtextoutputmode="None"
						imagedataembedinhtml="true"
						serversleepfordebug="0"
						allowcopy="true"
						// HeaderFooterEditable={params&&params.formView === "Normal" ? "fasle" : "true"} // 页眉页尾是否可操作
						supportactivex="false"
						pixelpagespacing="5"
						clientcontextmenutype="Custom" // 设置右键菜单，要把值设为Custom才行
						usedcwriterminijs="True"
						autozoom2="true"
						customcssstring="
              ::-webkit-scrollbar {width: 10px;height: 10px;}
              ::-webkit-scrollbar-thumb {border-radius: 5px;
                -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);background: #349dee; }
              ::-webkit-scrollbar-track {-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
                border-radius: 0;background: #eaedf1;}"
						showdebuginfo="false"
						registercodeindex="0"
					// fileprintautoclose="false" // 避免打印预览窗口会突然关闭问题
					></div>}

					<div
						id={this.editorID + 'btrPrintPreview'}
						style={{ zIndex: '1000', border: '1px solid black', backgroundColor: '#cccccc', display: 'none' }}
					>
						<input type="button" value={this.setMessage('ElectronicCaseTemplatePrint', 'descripts', '打印')} onClick={this.PrintDocument} className="button" style={{ margin: '0 12px' }} />
						<input type="checkbox" id={this.editorID + 'chkJumpPrint'} onClick={(e) => this.handleJumpPrint(e.target.checked)} />
						<label htmlFor={this.editorID + 'chkJumpPrint'} style={{ marginLeft: '3px' }}>{this.setMessage('ElectronicCaseTemplateResume', 'descripts', '续打')}</label>
						<input type="checkbox" id={this.editorID + 'chkMouseDragScroll'} onClick={(e) => this.handleSetMouseDragScroll(e.target.checked)} style={{ marginLeft: '12px' }} />
						<label htmlFor={this.editorID + 'chkMouseDragScroll'} style={{ marginLeft: '3px' }}>{this.setMessage('ElectronicCaseTemplateMouse_drag_selection', 'descripts', '鼠标拖拽选择')}</label>
						<input style={{ marginLeft: '12px' }} type="checkbox" id={this.editorID + 'chkBoundsSelection'} onClick={(e) => this.handleBoundsSelection(e.target.checked)} />
						<label htmlFor={this.editorID + 'chkBoundsSelection'} style={{ marginLeft: '3px' }}> 区域选择打印 </label>
						<input type="button" value={this.setMessage('ElectronicCaseTemplateClose_print_preview', 'descripts', '关闭打印预览')} style={{ marginLeft: '12px' }} onClick={this.ClosePrintPreview} className="button" />
					</div>
				</div>
				{/* 页面设置 */}
				<SettingsDocumentSize onRef={this.documentSetRef} ctlDom={document.getElementById(this.editorID)} />

				<Modal
					title={this.setMessage('ElectronicCaseTemplateBinding_CDS', 'descripts', '绑定自定义数据集')}
					visible={visible}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
				>
					<div style={{ maxHeight: '500px', overflow: 'auto' }}>
						<Tree loadData={this.onLoadData} selectedKeys={modalSelectedKeys} onSelect={this.modalOnSelect}>
							{this.renderCustomDataSetTreeNodes(customDataSet)}
						</Tree>
					</div>
				</Modal>

				<Modal
					title="病历模板插入"
					visible={courseOfDiseaseVisible}
					onOk={this.handleCourseOfDiseaseOk}
					okButtonProps={{
						loading: courseOfDiseaseLoading
					}}
					style={{ minWidth: '1400px', minHeight: '600px' }}
					onCancel={this.handleCourseOfDiseaseCancel}
				>
					<div style={{ width: "100%", height: '600px' }}>
						<Row>
							<Col span={16} style={{ height: '600px' }}>
								病历模板：<Select onChange={this.handleCourseOfDiseaseChange} value={courseOfDiseaseValue} style={{ width: '300px', marginBottom: "12px", marginRight: "24px" }} placeholder="请选择">
									{templateSelectOption}
								</Select>
								<Checkbox checked={forcedPageChange} onChange={this.handleForcedPageChange}>打印时是否单独一页</Checkbox>
								<div style={{ height: "calc(100% - 42px)" }}>
									<CourseOfDiseaseTemplate
										onRef={this.handlePreviewTemplateRef}
										handleReload={this.loadCourseOfDiseaseTemplate} // 重新加载
										getKnowledgeBaseTreeData={this.getChildKnowledgeBaseTreeData}
										customDataTableData={customDataTableData} // 自定义列表数据
									/>
								</div>
							</Col>
							<Col span={8} style={{ height: '600px' }}>
								<CaseInformationPageTabs
									handleQuote={this.Spechars} setKnowledgeBaseXMl={this.setKnowledgeBaseXMl} onRef={this.handleCaseInformationRef}
									modalRowData={this.state.modalRowData} treeSelectData={this.state.treeSelectData} compileVNum={this.compileVNum}
									knowledgeBaseAssignment={this.courseOfDiseaseKnowledgeBaseAssignment} showOnly="knowledgeBase"
								/>
							</Col>
						</Row>
					</div>
				</Modal>

				<Modal
					title="历史病历"
					visible={historicalKnowledgeBase}
					onOk={this.handleHistoricalKnowledgeBaseOk}
					style={{ minWidth: '60vw' }}
					onCancel={this.handleHistoricalKnowledgeBaseCancel}
				>
					<div className="add-department" style={{ width: "100%", height: "500px" }}>
						<Tabs
							activeKey={activeTabs}
							onChange={this.handleTabsCallback}
							tabPosition="left"
							type="card"
							className="new_department_tabs"
							style={{ width: '100%', height: "100%", overflow: "auto", border: "1px solid #ddd" }}
						>
							<TabPane tab={<span title="测试模板1">{"测试模板1"}</span>} key="1">
								<div style={{ height: "500px", padding: "24px", boxSizing: "border-box", lineHeight: "24px", textIndent: "2em", borderLeft: "1px solid #ddd" }}>
									测试模板1
								</div>
							</TabPane>
							<TabPane tab="测试模板2" key="2">
								测试模板2
							</TabPane>
							<TabPane tab="测试模板3" key="3">
								测试模板3
							</TabPane>
						</Tabs>
					</div>
				</Modal>

				<Modal
					title="诊断录入"
					visible={diagnosisSearch}
					onOk={() => this.handleDiagnosisSearchOk("confirm")}
					style={{ minWidth: '75vw' }}
					onCancel={this.handleDiagnosisSearchCancel}
					className="electronic-case-template-modal"
				>
					<div style={{ width: "100%" }}>
						<ShowDiagnosisModal onRef={this.showDiagnosisRef} handleDiagnosisSearchOk={this.handleDiagnosisSearchOk} />
					</div>
				</Modal>

				<Modal
					title="医嘱录入"
					visible={medicalOrderVisible}
					onOk={() => this.handleMedicalOrderOk('confirm')}
					style={{ minWidth: '75vw' }}
					onCancel={() => this.setState({ medicalOrderVisible: false })}
					className="electronic-case-template-modal"
				>
					<div style={{ width: '100%', height: '55vh' }}>
						<DoctorAdviceStepPage
							patStatus="1"
							heightVH={46}
							componentSourse="EMR" // 用于区分住院，列表数据保存之后是否清空
							// adviceList={this.state.adviceList}
							// ordPriorityID={this.state.priorityID}
							hideStatus={false}
							onRef={ref => this.depAdviceRef = ref}
							handleMedicalOrderOk={this.handleMedicalOrderOk}
						// dstroyAdviceList={this.dstroyAdviceList.bind(this)}
						/>
					</div>
				</Modal>

				<Modal
					title="动态下拉列表选择"
					visible={dropDownSearch}
					onOk={this.handleDropDownSearchOk}
					style={{ minWidth: '600px', minHeight: '300px' }}
					onCancel={this.handleDropDownSearchCancel}
				>
					<div style={{ width: "100%", height: '370px' }}>
						<div style={{ marginBottom: "12px" }}>
							{/* 代码：<Input
								title="输入内容后可回车检索"
								placeholder="请输入( Enter )"
								value={selectCode}
								style={{ width: '150px', marginRight: "12px" }}
								onChange={this.getSelectCodeValue}
								onPressEnter={this.handleQuery}
							/> */}
							描述：<Input
								title="输入内容后可回车检索"
								placeholder="请输入( Enter )"
								value={selectDesc}
								style={{ width: '250px', marginRight: "12px" }}
								onChange={this.getSelectDescValue}
								onPressEnter={this.handleQuery}
							/>
							<Button type="primary" onClick={this.handleQuery}>查询</Button>
						</div>
						<div
							tabIndex={1}
							onKeyDown={this.handlePublicModalTableOnKeydown}
							style={{ outline: 'none' }}
						>
							<PubilcTablePagination
								param={tableParam}
								handelThis={this}
								onRef={this.onModalRef}
								onClickRowPublic={this.onClickRowPublic}
								setRowClassNamePublic={this.setRowClassNamePublic}
								id="gundong"
							/>
						</div>
					</div>
				</Modal>
				<Modal
					title="当前病历数据有更新，请选择需要更新的数据"
					visible={contentChangeVisible}
					onOk={this.handleContentChangeVisiblehOk}
					style={{ minWidth: '800px', minHeight: '300px' }}
					onCancel={this.handleContentChangeVisiblehCancel}
				>
					<div style={{ width: "100%", height: '370px' }}>
						<Table
							columns={this.contentChangeColumns}
							dataSource={contentChangeTableData}
							scroll={{ x: 500, y: 335 }}
							rowSelection={contentChangeRowSelection}
							bordered
							rowKey={(data) => {
								return data.key
							}}
							pagination={false}
							className="table-body-height" />
					</div>
				</Modal>
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName={selectRowData && selectRowData.baseDataColumn ? selectRowData.baseDataColumn : 'ElectronicCaseTemplate'}
					configType="C"
					onRef={this.onMainColumnRef}
					reloadData={selectRowData && selectRowData.baseDataColumn ? () => this.getModalColumns(selectRowData.baseDataColumn) : this.getChineseAndEnglishData}
				/>

				{/* 查找替换 */}
				<EMRFindReplace onRef={ref => this.findReplaceRef = ref} handleSearchText={this.handleSearchText} handleReplaceText={this.handleReplaceText} />

				{/* 同步模板信息 */}
				<UpdateTemplateData onRef={ref => this.updateTemplateRef = ref} />

				<Modal
					width="90vw"
					title="DRG审核"
					bodyStyle={{ padding: 0 }}
					visible={DRGVisible}
					footer={null}
					onCancel={() => this.setState({ DRGVisible: false })}
				>
					<div style={{ height: '75vh', overflow: 'auto' }}>
						<iframe
							style={{ width: '100%', height: '100%' }}
							ref="iframe"
							src={DRGUrl}
							scrolling="auto"
							frameBorder="0"
						/>
					</div>
				</Modal>

				{/* 修改病程单独页标志 */}
				<PublicModalFormHooks
					width="520px"
					title={newPageRowData?.title || '病程单独页标志修改'}
					onRef={ref => this.newPageModalRef = ref}
					formData={newPageFormData}
					rowData={newPageRowData}
					handleSave={this.handleNewPageSave}
				/>
			</div>
		)
	}
}
